Use filter to implement character set settings for all pages in the project

        Occasionally, when writing a project, you may encounter the problem of Chinese garbled characters. You can add the following two lines of code to the garbled page to solve the problem of Chinese garbled characters.

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

         But in this case, one is more troublesome to add to all pages, and the other is a bit messy. For example, if there are too many lines of code, these two lines of code are often not found. Now you can use the filter filter to set the character set to all pages. UTF-8;

        The following is CharEncodingFilter.java

package com.student.filter;

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

/**
 * @Description
 * @Author single continuation
 * @Date 2016/10/24 16:19
 */
@WebFilter(filterName = "CharEncodingFilter")
public class CharEncodingFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

         Then configure the filter in the web.xml file, the code is as follows

<filter>
        <filter-name>CharEncodingFilter</filter-name>
        <filter-class>com.student.filter.CharEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

         This way all pages in the project can be set to UTF-8

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326606682&siteId=291194637