在项目中会遇到这样的需求,通过form表单或则ajax提交数据的时候会出现中文乱码的情况,这个时候就需要在前端与后台设置好同样的编码格式,但是前后台这么多业务逻辑,如果这样做的话会很麻烦,于是就相应出现了字符编码过滤器,这里实现了如果前端声明了字节编码那么就不动,如果未做声明则配置其字符编码为utf-8格式,代码如下:
package com.demo.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * 字符编码过滤器 * @author zhangdi * */ public class CharacterEncodingFilter implements Filter{ //字符编码 private String encoding; @Override public void destroy() { System.out.println("被销毁"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("完成过滤请求操作"); request.setCharacterEncoding(encoding); chain.doFilter(request, response); System.out.println("完成过滤相应操作"); } @Override public void init(FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter("encoding"); if(encoding==null){ encoding = "utf-8"; } } }
注意不要忘了在web.xml中配置声明:
<!-- 字符编码过滤器 --> <filter> <filter-name>encoding</filter-name> <filter-class>com.demo.filter.CharacterEncodingFilter</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>*.do</url-pattern> </filter-mapping>
这里配置的过滤范围是所有以.do结尾的接口