1. 程式人生 > >Filter的細節三學習筆記

Filter的細節三學習筆記

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的細節三學習筆記