码迷,mamicode.com
首页 > 其他好文 > 详细

Filter的细节三学习笔记

时间:2018-04-19 17:41:46      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:Filter的细节三学习笔记

当需要过滤include请求的资源时,可以设置dispatcher为INCLUDE过滤方式
d)当需要过滤error请求的资源时,可以设置dispatcher为ERROR过滤方式
注意:一定在要web.xml文件声明错误代码或类型
`<error-page>
<error-code>500</error-code>
<location>/sys_500.jsp</location>
</error-page>

<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/*</url-pattern>

<dispatcher>ERROR</dispatcher>

</filter-mapping>
`

e)对于过滤Servlet资源时,即可使用url-pattern,又可以使用servlet-name
f)一个Filter可以过滤1个或N个资源

</filter>
<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/FromServlet</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/ToServlet</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter>`

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 MappingFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        System.out.println("MappingFilter::doFilter():A");
        chain.doFilter(request,response);
        System.out.println("MappingFilter::doFilter():B");
        System.out.println("模拟正在写日志Log4J");
    }
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

//
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 ToServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        System.out.println("ToServlet::doGet()");
        //int i = 10 / 0;
    }
}
//
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 FromServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        System.out.println("FromServlet::doGet()");
        request.getRequestDispatcher("/ToServlet").forward(request,response);
        //request.getRequestDispatcher("/ToServlet").include(request,response);
    }
}

Filter的细节三学习笔记

标签:Filter的细节三学习笔记

原文地址:http://blog.51cto.com/357712148/2105470

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!