写法:
@WebListenerpublic class contextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { }}
实例————配置加载————(通过ServletContextListener将web.xml 中的配置信息加载到 ServletContext中 便于servlet 通过req.getServletContext().getAttribute(“xxx”)方法访问)
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
contextListener:
@WebListenerpublic class contextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println(" contextListener contextInitialized"); ServletContext servletContext= servletContextEvent.getServletContext(); String url=servletContext.getInitParameter("url"); String topic=servletContext.getInitParameter("topic"); Config config=new Config(); config.setTopic(topic); config.setUrl(url); servletContext.setAttribute("config",config); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println(" contextListener contextDestroyed"); }}
Cpnfig
public class Config { private String url; private String topic; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; }}
testServlet:
@WebServlet("/testServlet")public class testServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Config config= (Config) req.getServletContext().getAttribute("config"); System.out.println(config.getTopic()); }}
截图
未访问/testServlet
访问后
什么是监听器:
监听器是一个实现了特定接口的普通Java类,用于监听其他对象的创建和销毁,监听其他对象的方法执行和属性改变; avaweb里面的监听器:
作用:监听域对象的创建和销毁,比如request/session/context
分类:
ServletContextLitener HttpSessionListener ServletRequestListener
监听器的实现步骤:
(1)创建一个普通的Java类 (2)让该类实现监听器的接口 (3)在该类中实现监听器接口的所有方法
(4)旧版的在web.xml文件中通过标签来配置监听器,新版使用 @WebListener