Filter的细节三学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的细节三学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

[Python笔记]Python学习笔记三

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

《游戏引擎架构》笔记三

Python 3学习笔记

过滤器 Filter

Filter 禁止浏览器缓存动态资源,例如JSP资源 -学习笔记