ServletContex是 servlet上下文,是一个代表了整个项目的对象,全局唯一,项目内部所有servlet都能共享这个对象中保存的数据所以 ServletContext 又叫全局应用程序共享对象。
ServletContext对象在服务器启动的时候创建,服务器关闭的时候销毁。它共用四种获取方式
//第一种。 通过 GenericServlet 提供的 getServletContext() 方法
ServletContext servletContext = this.getServletContext();
//第二种。通过 ServletConfig 提供的 getServletContext() 方法
ServletContext servletContext = this.getServletConfig().getServletContext();
//第三种。通过 HttpSession 提供的 getServletContext() 方法
ServletContext servletContext = req.getSession().getServletContext();
//第四种。通过 HttpServletRequest的 getServletContext() 方法
ServletContext servletContext = req.getServletContext();
ServletContext的作用:
在各个 servlet 间实现全局数据共享
获取web.xml配置的上下文参数context-param
获取项目路径,读取 Web 应用下的资源文件
因为ServletContext的全局性,所以可以在Servlet之间共享数据
方 法 | 说 明 |
---|---|
Object getAttribute(String attributeName) | 获取 attributeName(属性名称)对应的 object |
void setAttribute(String attributeName, Object object) | 将object保存到ServletContext中 |
Enumeration getAttributeNames() | 返回 application 对象中所有的 attributeName |
void removeAttribute(String objectName) | 删除 application 对象中指定 attributeName 的属性 |
String getServerInfo() | 获取当前 Servlet 的版本信息 |
public class Test1Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Userinfo userinfo = new Userinfo("张三","123456");
//获取context将对象userinfo保存进去
ServletContext context = request.getServletContext();
context.setAttribute("userinfo",userinfo);
}
}
public class Test2Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
//从context对象中获取userinfo
Userinfo userinfo = (Userinfo) context.getAttribute("userinfo");
System.out.println("username:"+userinfo.getUsername());
//获取所有的attributeName
Enumeration<String> attributeNames = context.getAttributeNames();
while (attributeNames.hasMoreElements()){
System.out.println(attributeNames.nextElement());
}
//移除userinfo对象
context.removeAttribute("userinfo");
Userinfo userinfo1 = (Userinfo) context.getAttribute("userinfo");
if(userinfo1 == null){
System.out.println("移除成功");
}
}
}
获取在XML文件中上下文初始化的参数
方 法 | 说 明 |
---|---|
Enumeration getInitParameterNames() | 获取所有的param-name |
String getInitParameter(paramName) | 根据param-name获取相应值 |
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>nameparam-name>
<param-value>yuparam-value>
context-param>
<context-param>
<param-name>genderparam-name>
<param-value>男param-value>
context-param>
web-app>
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//获取ServletContext对象
ServletContext servletContext = this.getServletContext();
//获取全局param-name
Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
while (initParameterNames.hasMoreElements()){
String paramName = initParameterNames.nextElement();
String paramValue = servletContext.getInitParameter(paramName);
out.write("param-name:"+paramName+".paramValue:"+paramValue+"
");
}
out.close();
}
访问Test1Servlet时会将页面转发到指定的转发路径,访问路径不会改变,但是会显示转发后的页面
public class Test1Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//获取ServletContext对象
ServletContext context = this.getServletContext();
//设置需要转发的路径
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/Test2Servlet");
//开始转发
requestDispatcher.forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
因为是使用的Tomcat部署项目,我们的项目随然显示在idea 的路径中,但实际上还是部署到了Tomcat的webapps中了,如果直接在代码中写相对、绝对路径,很可能会导致找不到文件,而直接写磁盘路径的话,在更换服务器后一样会出现找不到资源的情况,所以ServletContext提供了getRealPath()获取项目路径,这样不管再怎么更换服务器都能获取到正确的路径。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//获取ServletContext对象
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("index.xml");
out.write("获取的路径:"+realPath+"");
Set<String> servlet = servletContext.getResourcePaths("/");
out.write("获取的web资源:");
servlet.forEach(s -> out.write(s+","));
out.write("");
}