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