MENU

JavaWeb常见的乱码问题解决方案总结

March 17, 2020 • Read: 103 • Note,JavaWeb

第一种(推荐),使用类+配置实现全局

添加一个实现编码utf-8的类,

无需记住,看懂即可,复制粘贴就完事.

public class EncodingFilter implements Filter {

    private String encoding="utf-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (filterConfig.getInitParameter("encoding")!=null){
            encoding=filterConfig.getInitParameter("encoding");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

在web.xml中加入配置

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.xn2001.oa.global.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/**</url-pattern>
    </filter-mapping>

第二种,单页面操作

        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

第三种,设置虚拟机(不推荐)

-Dfile.encoding=GBK 或者Dfile.encoding=UTF-8


本站所有未注明转载的文章均为原创,并采用CC BY-NV-SA 4.0 授权协议,转载请注明来源。

Last Modified: June 5, 2020
Archives QR Code
QR Code for this page
Tipping QR Code