javax.servlet.Filter類中主要有三個方法。
public void destroy(); //銷毀對象 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); //執行Filter響應的代碼寫在這個方法里 public void init(FilterConfig fConfig); //初始化對象
先建立一個web工程,建立兩個JSP頁面,而本文中的程序主要實現的就死利用doFilter()方法,從index1.jsp跳轉到index2.jsp。
建立好index1.jsp頁面和index2.jsp。
下面配置一下WEB.xml,配置WEB.xml中的Filter和配置Servlet一樣,類名和類包,然后是映射,很簡單。
<filter > <filter-name>filter</filter-name> <filter-class>com.Filter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> //應該與上面的filter-name一致 <url-pattern>*.action</url-pattern> //任何以.action結尾頁面請求都可以被返回給filter </filter-mapping>
然后是index1.jsp頁面,只需要寫一個
<a href = "forward.jsp">點擊此跳轉致index2.jsp</a>
測試一下是否跳轉成功即可,index2.jsp內容隨便(this is my page!)。
接下來是配置com包中Filter類中的doFilter()方法。具體代碼如下:
HttpServletRequest req = (HttpServletRequest) request; String path = req.getServletPath(); //此方法只有HttpServletRequest類中有,獲得頁面響應的路徑 System.out.println(path); if("/forward.action".equals(path)){ //如果與index1.jsp中href中的地址一致則跳轉index2.jsp request.getRequestDispatcher("index2.jsp").forward(request,response); }else{ //如果不一致則跳轉index3.jsp頁面 request.getRequestDispatcher("index3.jsp").forward(request,response); } chain.doFilter(request, response);
以上。