JavaWeb 解决乱码问题

自写过滤器解决
文件结构
image

代码配置
EncondingFiler

package filter;

import javax.servlet.*;
import java.io.IOException;

public class EncondingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

Web.xml 配置
<!--    过滤器解决乱码问题-->
    <filter>
        <filter-name>enconding</filter-name>
        <filter-class>filter.EncondingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>enconding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

SpringMVC 直接配置解决

<filter>
        <filter-name>enconding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>enconding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>enconding</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>

原文地址:https://www.cnblogs.com/femme/p/17441161.html