servlet中的ServletContext
设置、获取ServletContext配置信息
与ServletConfig不同的是,所有Servlet共享一份ServletContext
-
在web.xml中设置配置信息
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"version="6.0"><context-param><param-name>key1</param-name><param-value>a</param-value></context-param><context-param><param-name>key2</param-name><param-value>b</param-value></context-param> </web-app>
-
在service方法中读取
public class ServletTest extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext servletContext = this.getServletContext();// 获取指定的配置信息String value = servletContext.getInitParameter("key2");System.out.println(value);// 批量获取配置信息Enumeration<String> initParameterNames = servletContext.getInitParameterNames();while(initParameterNames.hasMoreElements()) {String key = initParameterNames.nextElement();System.out.println(key + "=" + servletContext.getInitParameter(key));}} }
通过ServletContext获取项目实际部署的根路径:getRealPath()
ServletContext servletContext = this.getServletContext();
// 获取项目实际部署的根路径(绝对路径)
String rootPath = servletContext.getRealPath(""); // D:\workspace\javawebproject\out\artifacts\demo1_war_exploded\
// 获取项目实际部署的根目录下的static路径(绝对路径)
String staticPath = servletContext.getRealPath("static"); // D:\workspace\javawebproject\out\artifacts\demo1_war_exploded\static
通过ServletContext获取项目的访问路径:getContextPath()
ServletContext servletContext = this.getServletContext();
// 获取项目的访问路径
String accessPath = servletContext.getContextPath(); // /demo1
域对象
ServletContext是应用域,作用于整个应用,所有Servlet都可访问到,可用于存储和传递数据,实现各个Servlet之间的通信
在servlet1中存储数据,供Servlet2获取
// Servlet1
public class Servlet1 extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse resp) {// 在servlet1中存储数据,供Servlet2获取ServletContext servletContext = this.getServletContext();servletContext.setAttribute("aaa", 123);}
}
// Servlet2
public class Servlet2 extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse resp) {// 供Servlet2中获取ServletContext servletContext = this.getServletContext();String value = (String) servletContext.getAttribute("aaa");System.out.println(value);// 移除数据servletContext.removeAttribute("aaa");}
}