ServletContext代表的是一个web应用的环境(上下文)对象,ServletContext对象内部封装的是该web应用的信息。
一 个 w e b 应 用 只 有 一 个 S e r v l e t C o n t e x t 对 象 。 \color{red}{一个web应用只有一个ServletContext对象。} 一个web应用只有一个ServletContext对象。
第一种:
ServletContext servletContext = config.getServletContext();
第二种(常用):
ServletContext servletContext1 = this.getServletContext();
<context-param>
<param-name>testStrparam-name>
<param-value>helloWorldparam-value>
context-param>
通过ServletContext获得初始化参数:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//获得初始化参数
String testStr = servletContext.getInitParameter("testStr");
System.out.println(testStr);
}
通过浏览器访问,控制台输出:
helloWorld
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//获的资源相对于该web的相对路径
String realPath = servletContext.getRealPath("index.jsp");
System.out.println(realPath);
}
通过浏览器访问,控制台输出:
F:\IDEAworkspace\JavaEEDemo\out\artifacts\JavaEEDemo_war_exploded\index.jsp
域对象:
域对象是服务器在内存上创建的存储空间,用于在不同动态资源(servlet)之间传递与共享数据。
域对象通用方法:
方法 | 描述 |
---|---|
setAttribute(String name,Object value); | 向域对象中添加数据,添加时以key-value形式添加 |
getAttribute(String name); | 根据指定的key读取域对象中的数据 |
removeAttribure(String name); | 根据指定的key从域对象中删除数据 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得ServletContext对象
ServletContext servletContext = this.getServletContext();
//向域对象中存入数据
servletContext.setAttribute("str", "helloWorld");
//从域对象中取出数据
String str = (String) servletContext.getAttribute("str");
//从域对象中删除数据
servletContext.removeAttribute("str");
}
ServletContext存储数据的特点:
全局共享,里面的数据所有动态资源都可以写入和读取。
核心方法:
getServletContext().getContextPath();
示例:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得工程名字
String contextPath = getServletContext().getContextPath();
System.out.println(contextPath);
}
通过浏览器访问,控制台输出:
/JavaEEDemo