过滤器链-学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过滤器链-学习笔记相关的知识,希望对你有一定的参考价值。

a)一个Web应用可以有0个或多个Filter,多个Filter的组合就是过滤器链
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 {
    }

}

技术分享图片

以上是关于过滤器链-学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

学习笔记:python3,代码片段(2017)

GNU工具链学习笔记

[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段

Python数据结构学习笔记——链表:无序链表和有序链表

区块链学习笔记之以太坊

区块链学习笔记之以太坊