'Why is it invalid for filter to set Chinese encoding for all web pages?

Recently, I encountered a problem when I learn web filter. I set the filter in web.xml to operate on all web pages. The settings are as follows

<filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

You can see that all web pages are set to be filtered here.

The function of this filter is to make the web page use gb2312 encoding, the code is as follows:

@WebFilter(filterName = "EncodingFilter")
public class EncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("gb2312");
        chain.doFilter(request, response);
    }
}

The test servlet is as follows

@WebServlet(name = "DealWithServlet", value = "/DealWithServlet")
public class DealWithServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        // print chinese characters
        out.println("word is " + "单词");
    }
}

the setting in web.xml are as follows:

<servlet>
    <servlet-name>DealWithServlet</servlet-name>
    <servlet-class>Servlet.DealWithServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DealWithServlet</servlet-name>
    <url-pattern>/Servlet/DealWithServlet</url-pattern>
</servlet-mapping>

configuration are as follows: configuration

The project structure is as follows:

  • servlet_demo2
    • src
      • filter
        • EncodingFilter.class
      • Servlet
        • DealWithServlet.class

Then I entered the relevant webpage and found that it cannot display Chinese. What is going on here? The address entered is

http://localhost:8088/servlet_demo2/Servlet/DealWithServlet

The actual effect is as follows:actual effect

Could anyone possibly tell me how i can solve this problem?



Solution 1:[1]

i forget to add

response.setCharacterEncoding("gb2312");

in EncodingFilter.class.
Add this code, the servlet can display Chinese normally

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rolling apaike