過濾器鏈-學習筆記
阿新 • • 發佈:2018-04-18
過濾器鏈-學習筆記a)一個Web應用可以有0個或多個Filter,多個Filter的組合就是過濾器鏈
b)多個Filter的執行先後順序,與web.xml文件中配置的順序有關
c)chain.doFilter(request,response)具有二義性:
b)多個Filter的執行先後順序,與web.xml文件中配置的順序有關
c)chain.doFilter(request,response)具有二義性:
>如果有下一個Filter時,將請求轉發給下一個Filter
>如果無下一個Filter時,將請求轉發給Web資源(serlvet/jsp/html)
d)可以將web資源中的一些公共代碼,提取出來,放入Filter中
`<filter> <filter-name>FilterDemo1</filter-name> <filter-class>cn.web.servlet.filter.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo1</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>FilterDemo2</filter-name> <filter-class>cn.web.servlet.filter.FilterDemo2</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ` `import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); response.getWriter().write("歡迎學習Servlet下篇"); }
}`
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class FilterDemo2 implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { response.setContentType("text/html;charset=UTF-8"); System.out.println("第二個攔截器:Filter2"); //放行請求[調用] chain.doFilter(request,response); } public void init(FilterConfig filterConfig) throws ServletException { } }
過濾器鏈-學習筆記