一 filter是servlet2.3新增加的功能,功能是在请求到达servlet之前和返回之前可以修改request和response。
还可以通过继承HttpServletRequestWrapper去重写request和response的一些方法
二 listener的作用查了一些资料没有看到想要的答案,然后决定自己去看看源码,以web.xml中spring配置的listener为例子
1 org.springframework.web.context.ContextLoaderListener
2 ContextLoaderListener的源码:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
public void contextInitialized(ServletContextEvent event) {
this.initWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
this.closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
public interface ServletContextListener extends EventListener {
void contextInitialized(ServletContextEvent arg0);
void contextDestroyed(ServletContextEvent arg0);
}
分析:
1 ServletContextListener是javax.context包里面的,看这两个方法就是conext初始化和销毁的时候
2 这个context就是ServletContext,ServletContext是Servlet的接口,一个web应用只有一个ServletContext,所有应用共用一个ServletContext
3 applicationContext实现了Servlet接口,applicationContext类中包含了StandardContext对象
4 StandardContext对象:一个web应用对应一个Context容器,也就是一个StandardContext类(其中ContextConfig类负责解析配置文件xml,这个类会被加到StandardContext类中),StandardContext的子容器是Wrapper对象,而Wrapper包装的就是Servlet了。StandardContext(Context容器)---Wrapper(servlet包装类)---servlet。
5 所以从servlet中获取的ServletContext,其实是获得了ApplicationConext,也就获得了context容器StandardContext,可以这么说:一个ServletContext就代表着一个web应用,一个Context容器。
6 ServletContext如何获取,如果你用的是struts,this.getServlet().getServletContext(),原因是struts的action中有servlet,而所有servlet就可以获得ServletContext。
7 ServleContext有什么用:设置全局参数,比如全局的根路径(我暂时用到的地方就是这里了),下面是最简单的例子
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
event.getServletContext().setAttribute("ctx", event.getServletContext().getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
}
在jsp中直接用<c:out value="${ctx }"/>