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

添加一个实现编码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



腾讯云社区邀请各位技术博主加入,福利多多噢!
Last modification:June 5th, 2020 at 11:33 am
如果觉得我的文章对你有用,请随意赞赏