第一种(推荐),使用类 配置实现全局
添加一个实现编码utf-8的类,
无需记住,看懂即可,复制粘贴就完事.
代码语言:javascript复制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中加入配置
代码语言:javascript复制 <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>
第二种,单页面操作
代码语言:javascript复制 response.setContentType("application/json;charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
第三种,设置虚拟机(不推荐)
-Dfile.encoding=GBK
或者Dfile.encoding=UTF-8