1. 程式人生 > >Servlet的filter和listener,重點了解ServletContext

Servlet的filter和listener,重點了解ServletContext

一 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 }"/>