javax.servlet.Filter類中主要有三個方法。
public void destroy(); //銷毀對象public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); //執(zhí)行Filter響應(yīng)的代碼寫在這個方法里public void init(FilterConfig fConfig); //初始化對象
先建立一個web工程,建立兩個jsp頁面,而本文中的程序主要實(shí)現(xiàn)的就死利用doFilter()方法,從index1.jsp跳轉(zhuǎn)到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> //應(yīng)該與上面的filter-name一致 <url-pattern>*.action</url-pattern> //任何以.action結(jié)尾頁面請求都可以被返回給filter </filter-mapping>
然后是index1.jsp頁面,只需要寫一個
<a href = "forward.jsp">點(diǎn)擊此跳轉(zhuǎn)致index2.jsp</a>
測試一下是否跳轉(zhuǎn)成功即可,index2.jsp內(nèi)容隨便(this is my page!)。
接下來是配置com包中Filter類中的doFilter()方法。具體代碼如下:
HttpServletRequest req = (HttpServletRequest) request; String path = req.getServletPath(); //此方法只有HttpServletRequest類中有,獲得頁面響應(yīng)的路徑 System.out.PRintln(path); if("/forward.action".equals(path)){ //如果與index1.jsp中href中的地址一致則跳轉(zhuǎn)index2.jsp request.getRequestDispatcher("index2.jsp").forward(request,response); }else{ //如果不一致則跳轉(zhuǎn)index3.jsp頁面 request.getRequestDispatcher("index3.jsp").forward(request,response); } chain.doFilter(request, response);
以上。
新聞熱點(diǎn)
疑難解答
圖片精選