Filter writing steps
- Write a class that implements the javax.servlet.Filter interface
- Rewrite all the methods in the interface, where the doFilter method performs the filtering function
- Configure filter
- Configure in web.xml
- 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:
- 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.
- Execute the doFilter() method and call chain.doFilter(request, response) inside the method. Its role is to release.
- If it is not released, the request is intercepted. The request could not reach the web resource.
- After release, the web resource is executed. When the response comes back, it will pass through the filter again.