Web 应用程序一旦部署到容器上之后,容器就要为Web应用实例化一个 ServletContext 对象, ServletContext 是一个全局的储存信息的空间,包含了整个Web应用程序的运行环境信息,服务器关闭时才销毁。
- ServletContext:所有用户共用一个
- Session: 一个用户一个
- Request: 一个请求一个
ServletContext 获取
Listener 中获取 ServletContext
public class StartupServletListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
}
}
Filter 中获取 ServletContext
public class SetCharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext servletContext = filterConfig.getServletContext();
}
}
Servlet 中获取 ServletContext
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException {
ServletContext servletContext = this.getServletContext();
}
}
HttpServletRequest 获取
ServletContext servletContext = request.getSession().getServletContext();
ServletContext 应用
读取 web.xml 参数
web.xml
<context-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
Listener启动时读取指定参数
public class StartupServletListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("初始化数据库数据参数");
String driverClass = servletContextEvent.getServletContext().getInitParameter("driverClass");
System.out.println(driverClass);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
Listener启动时读取所有参数
public class StartupServletListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
Enumeration<String> enumer = servletContext.getInitParameterNames();
while (enumer.hasMoreElements()) {
String name = enumer.nextElement();
String value = servletContext.getInitParameter(name);
System.out.println(name + " = " + value);
}
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
读取资源文件
全文阅读:https://www.laobingbiji.com/page/202403281540300000000010148878.html