Write a filter to solve the global garbled problem

Filter writing steps

  1. Write a class that implements the javax.servlet.Filter interface
  2. Rewrite all the methods in the interface, where the doFilter method performs the filtering function
  3. Configure filter
    1. Configure in web.xml
    2. Use annotation @WebFilter

To solve the garbled code, you need to add this code: req.setCharacterEncoding("utf-8"); The character set should be consistent with the encoding of the web page

EncodingFilter.java:

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {
    
    

    public void init(FilterConfig config) throws ServletException {
    
    

    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
        HttpServletRequest request = (HttpServletRequest) req;
        // 判断是否是POST方法	在Tomcat8或以上中只有POST方法会出现乱码
        if ("POST".equals(request.getMethod())) {
    
    
            req.setCharacterEncoding("utf-8");	// 解决乱码	
        }
        chain.doFilter(req, resp);	// 这句话一定要执行 功能是放行	否则会一直阻塞在这里
    }

    public void destroy() {
    
    

    }

}

The execution process of the filter is as follows:

Insert picture description here

  1. The user sends a request for web resources. If the filter finds that the access address of the web resource matches the current filter, the code in the filter is executed first.
  2. Execute the doFilter() method and call chain.doFilter(request, response) inside the method. Its role is to release.
  3. If it is not released, the request is intercepted. The request could not reach the web resource.
  4. After release, the web resource is executed. When the response comes back, it will pass through the filter again.

Guess you like

Origin blog.csdn.net/RookiexiaoMu_a/article/details/89422988