【Head First Servlets and JSP】笔记 28: 过滤器与包装器

2021-06-07 19:02

阅读:364

标签:package   code   for   没有   import   sch   dog   ram   服务器   

1、过滤器的执行顺序: 为第一梯队, servlet-name> 为第二梯队,梯队内的执行顺序和 DD 里的声明顺序相同。

When the container recives a request, it first finds all the filter mappings with a  that matches the request URI. This becomes the first set of filters in the filter chain.Next it finds all the filter mappings with a  that matches the request URI. This becomes the second set of filters in the filter chain.In both the sets the filters are executed in the order in which they are declared in the D.D.

 

2、可以对服务器中传递的请求进行过滤。

    BeerRequestsample.BeerRequestFilterLogFileNameUserlog.txtBeerRequest*.dojack
        dispatcher>REQUESTdispatcher> 
        dispatcher>INCLUDEdispatcher>
        dispatcher>FORWARDdispatcher>
        dispatcher>ERRORdispatcher>
    

 

3、过滤器应用实例

package sample;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter printWriter = resp.getWriter();
        printWriter.println("calls doGet(req, resp)");
        printWriter.println("测试能否输出中文");
        printWriter.close();
    }
}

filter :

package sample;

import javax.servlet.*;
import java.io.IOException;

public class Filter implements javax.servlet.Filter{

    private int visited;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setContentType("text/html");
        servletResponse.setCharacterEncoding("utf-8");
        visited ++;
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("visited = " + visited);
    }

    @Override
    public void destroy() {

    }
}

web.xml


         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    servletclass>sample.Servletclass>
    servlet/dofilterclass>sample.Filterclass>
    filterservlet

 

4、包装器略。

 

 

 


【Head First Servlets and JSP】笔记 28: 过滤器与包装器

标签:package   code   for   没有   import   sch   dog   ram   服务器   

原文地址:http://www.cnblogs.com/xkxf/p/7323908.html


评论


亲,登录后才可以留言!