JAVAEE filterSummary

1. Why do you need a filter?

The filter is equivalent to a door between the client and the server, just like a security guard. Function: For example, set the character set and permission control, etc.

 

2. Details; 

      * . Can only work on post requests

      * . Various matching patterns can be used:

              *.jsp (*. followed by a suffix) /servlet/* (all requests under a certain path) /* (match all)

 

      *  Note: When the client sends a request to the server, it will be intercepted (if it is forwarded from the servlet to another jsp page, it will not be intercepted at this time)

 

3. Java code:

package com.huxin.filter;

import java.io.IOException;
import javax.servlet.*;
public class SetCharacterEncodingFilter implements Filter {
        private String encoding ="";
        public void destroy() {}
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
	        servletRequest.setCharacterEncoding(encoding);
	        filterChain.doFilter(servletRequest, servletResponse);
        }
        public void init(FilterConfig filterConfig) throws ServletException {
          this.encoding =  filterConfig.getInitParameter("encoding");
        }
}


 

   <filter>
          <filter-name>SetCharacterEncodingFilter</filter-name>
          <filter-class>com.huxin.filter.SetCharacterEncodingFilter</filter-class>
        <init-param>
           <param-name>encoding</param-name>
           <param-value>utf-8</param-value>
        </init-param>
   </filter>
   <filter-mapping>
         <filter-name>SetCharacterEncodingFilter </filter-name>
         <url-pattern>/*</url-pattern>
   </filter-mapping>


Regarding the life cycle of filter:

When the tomcat container starts, the filter will be loaded, and the init() method will be called to assign an initial value to the encoding. When the life cycle ends, the destroy() method is called.

 

 Principle conjecture:

  It should also be a recursive implementation, similar to struts2 interceptors.

Guess you like

Origin blog.csdn.net/hu_xinxin/article/details/9265501