Detailed explanation of web layer filter in mvc

Posted by patnet2004 on Wed, 23 Feb 2022 11:22:40 +0100

web layer

Filter

Three technologies involved in the Web core
Servlet: server applet small program on the server side (mainly dealing with the part of request response)
Filter: filter, filter: leave the content you need and eliminate the unwanted content
Listener: listener

summary

Need to configure web XML (key)

filter creation steps

  1. Create class
  2. Implement javax servlet. Specification of filter (Interface)
/**
 * 1. Create class
 * 2. Implement javax servlet. Specification of filter (Interface)
 * 3. Inform tomcat that we have configured the filter (configured by web.xml)
 * 4. Write the filter code normally
 */
public class HelloFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * Execute the filtering method. This method will be executed every time the filter is executed. This method is equivalent to the service method of servlet
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("HelloFilter Executed A");
        //Release code
        filterChain.doFilter(request, response);

        System.out.println("HelloFilter Code after release B");
    }
    @Override
    public void destroy() {

    }
}

3. Inform tomcat that we have configured the filter (configure web.xml)

<!--

     <filter> notice tomcat We need to add a filter
        <filter-name>HelloFilter</filter-name>  filter Name of(alias) whole web.xml Must be unique in
        <filter-class>com.llz.web.a_filter.HelloFilter</filter-class> Location of filter,Fully qualified class name
    </filter>
    <filter-mapping> filter Mapping path configuration
        <filter-name>HelloFilter</filter-name> Use alias
        <url-pattern>/DemoServlet</url-pattern> Filter path of filter
    </filter-mapping>
-->
<filter>
    <filter-name>HelloFilter</filter-name>
    <filter-class>com.llz.web.a_filter.HelloFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>HelloFilter</filter-name>
    <url-pattern>/DemoServlet</url-pattern>
</filter-mapping>

4. Write the filter code normally

Implementation process of filter


Filter function: whole station code, filter illegal characters

How to create a filter

a. Configure web xml
b.@WebFilter annotation

/**
 * 1.Create class
 * 2.Implement javax servlet. Filter interface
 * 3.Configure web xml
 *     <filter>
 *         <filter-name>XmlFilter</filter-name>
 *         <filter-class>com.llz.web.b_filter.XmlFilter</filter-class>
 *     </filter>
 *     <filter-mapping>
 *         <filter-name>XmlFilter</filter-name>
 *         <url-pattern>/DemoServlet</url-pattern>
 *     </filter-mapping>
 *     Give Filter an interception path
 * 4.Write release code
 */
@WebFilter(urlPatterns = "/DemoServlet")
public class AnnoFilter implements Filter {

Other knowledge points of filter

life cycle

Meaning: when classes are created and destroyed
init: execute at the start of the project (only once): by default, the servlet is initialized the first time it accesses the servlet
doFilter: this method will be executed every time the access is intercepted
Destroy: destroy only once when the project is stopped

Configuration of interception path

URL pattern setting of servlet, access to servlet entry (four types)
Exact match: / a/b/c/Servlet
Incomplete match (directory match): / a/b/c/*
Suffix matching: * jsp *.html *.do *.abc
Default matching: / the above three types are not matched. The default matching is successfully executed (there is a default setting 404 in tomcat)

There are only three intercepting path settings for filter (intercepting after matching)
Exact match: / a/b/c/Servlet
Incomplete match (directory match): / a/b/c/*
Suffix matching: * jsp *.html *.do *.abc
filter has no default match

//If the accessed resource can be found after release, it will be displayed
//If no accessible resources are found after release 404
//No release: no matter whether the following resources can be accessed successfully or not, the response is composed of filter and whiteboard page

Interception mode configuration (use the default)

Filter execution timing

REQUEST: the default value, indicating that the REQUEST is intercepted at the beginning

FORWARD: request forwarding for interception

<filter>
     <filter-name>MyDispatcherFilter</filter-name>
     <filter-class>com.llz.web.d_dispatcher.MyDispatcherFilter</filter-class>
 </filter>
 <filter-mapping>
     <filter-name>MyDispatcherFilter</filter-name>
     <url-pattern>/DemoServlet</url-pattern>
     <!--to configure filter Timing of interception, Default value: REQUEST-->
     <!--FORWARD: Intercept when forwarding requests-->
     <dispatcher>FORWARD</dispatcher>
 </filter-mapping>

Filter chain

Multiple filters are allowed in the server. This group of filters is called filter chain
Filter chain xml, the order of execution, in xml, is web The configuration order of xml top-down filter is the execution order
Implementation order of Filter chain annotation Filter: class name determines order

Advantages and disadvantages of filter creation

xml :
Advantages: clear configuration, decoupling (decoupling, code relevance) and easy modification (all contents are together)
Disadvantages: configuration is troublesome, and a large amount of content needs to be written to represent a section of configuration

Notes:
Advantages: simple to use without requiring a large number of configurations
Disadvantages: it is not conducive to modify the annotations embedded in each class (the coupling degree is too high). It is recommended that the annotated classes should not be modified frequently

Total station code

/**
 * matters needing attention:
 * 1.urlPatterns = "/*" All resources in the server are processed
 * 2.Release is required and cannot affect the original business logic
 * chain.doFilter(req, resp);
 */
@WebFilter(filterName = "EncodingFilter" , urlPatterns = "/*")
public class EncodingFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("Filter executed");
        //Processing request response code
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //Release is required and cannot affect the original business logic
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    }
}

Filter filter illegal characters

@WebFilter(filterName = "IllEgalFilter",urlPatterns = "/*")
public class IllEgalFilter implements Filter {
    //Store dirty characters -- promotion is used to make multiple methods available
    List<String> list = new ArrayList<String>();
    /**
     * Initialization method: initialize the collection of dirty words here once
     */
    public void init(FilterConfig config) throws ServletException {
        //Store dirty characters
        //List<String> list = new ArrayList<String>();
        list.add("Uncle");
        list.add("Say");
        list.add("Your daughter");
    }
    /**
     * 1.List set ready to handle dirty words - initialized in init because it is initialized only once
     * 2.Get characters first in doFilter
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //Force object: use familiar objects
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        //Set code
        request.setCharacterEncoding("utf-8");
        response.setContentType("textml;charset=utf-8");

        //1. Get the request character
        String username = request.getParameter("username");
        System.out.println("filter Unprocessed in username:" + username);
        //2. Traverse the character set of dirty words
        for (String word : list) {
            //3. Judge whether the requested character contains dirty words. Each kind of dirty words must be judged
            if(username.contains(word)){//contains includes uncle to dance square dance. Uncle says your sister
                username = username.replaceAll(word  , "*");
            }
        }
        System.out.println("filter Processed in username:" + username);
        //The object passed in is the object after our transformation
        chain.doFilter(request, response );//Release
    }

    public void destroy() {
    }
}

Above code problem

Problem generation: request Getparameter ("key") obtains the original data and executes chain When dofilter (request, response) is released, it will still bring dirty words. (that is, it doesn't have the effect we want it to have)
Solution: just copy the request Just use the getparameter method (modify the code logic)

Solution: tomcat has considered this problem, so it has provided an implementation class of HttpServletRequest object.
Requirement: the class we create must inherit, but must provide a parameterized construct. Rewrite the method that we need to execute our own logic, and other methods call the parent method directly (this is the packaging idea)

Package code

public class MyHttpServletRequest extends HttpServletRequestWrapper{
    //Data prepared by illegal characters
    List<String> list = new ArrayList<String>();
    HttpServletRequest request2 ; //You can use the request object in your own class

    public MyHttpServletRequest(HttpServletRequest request) {
        super(request); //All the codes passed in to the parent class are implemented (all the codes that do not need to be copied here have been completed)
        this.request2 = request;
    }

    //All code parent classes that do not need to be copied have been completed
    //Consider the code that needs to be replicated
    @Override
    public String getParameter(String name) {
        //Prepare data
        list.add("Uncle");
        list.add("Say");
        list.add("Your daughter");

        //System. out. Println ("myhttpservletrequest -- > getparameter executed");
        if(name==null || "".equals(name)){//Prevent code error and parameter passing error
            return null; //Subsequent codes are no longer executed
        }
        //Get the original data
        String oldParameter = request2.getParameter(name);
        if(oldParameter==null || "".equals(oldParameter)){//Prevent code error and parameter passing error
            return null; //Subsequent codes are no longer executed
        }
        //Logic code - > there must be parameters and the requested data has been obtained
        for (String word : list) {
            //if(oldParameter.contains(word)){
                oldParameter = oldParameter.replaceAll(word , "*");
            //}
        }
        //As long as the last returned value is the processed string, the effect is achieved
        return oldParameter;
    }
 }

Modify the previous filter class

WebFilter(filterName = "IllEgalFilter",urlPatterns = "/*")
public class IllEgalFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    /**
     * 1.List set ready to handle dirty words - initialized in init because it is initialized only once
     * 2.Get characters first in doFilter
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //Force object: use familiar objects
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //Set code
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //The self-defined request modifies the method
        MyHttpServletRequest myHttpServletRequest = new MyHttpServletRequest(request);
        //The object passed in is the object after our transformation
        chain.doFilter(myHttpServletRequest, response );//Release
    }

    public void destroy() {
    }
}

Topics: Front-end Tomcat mvc