Java Filter工作原理

Java Filter工作原理_第1张图片

用户的请求可以理解为转化为两个方向
1. doFilter是一个viod方法.那么doFilter方法的前后都可以处理.
2.request 与 response一些参数的修改.
3.response.getWriter()输出流输出到用户浏览器端
4.Filter中一样可以对流进行获取,并增加输出.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        System.out.println("f1 start");
        chain.doFilter(request, response);
        System.out.println("f1 end");
    }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        // pass the request along the filter chain
        System.out.println("f2 start");
        chain.doFilter(request, response);
        //这里可以追加输出
        System.out.println(response.getWriter().append("f2"));
        System.out.println("f2 end");


    }
/**
 * Servlet implementation class S1
 */
@WebServlet("/S1")
public class S1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public S1() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("s1 start");

        response.getWriter().append("Served at: ").append(request.getContextPath());

        System.out.println("s1 end");

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
最后访问url的输出.

f1 start
f2 start
s1 start
s1 end
org.apache.catalina.connector.CoyoteWriter@100433ab
f2 end
f1 end

你可能感兴趣的:(Java)