POST中文乱码解决方案
以前,我都是自己编写一个filter,来实现编码,代码如下:
1 public class CharacterEncodingFilter implements Filter { 2 3 private final static Logger log= LoggerFactory.getLogger(CharacterEncodingFilter.class); 4 5 private String characterEncoding; //编码方式配置在web.xml文件中 6 private boolean enabled; //是否启用此Filter,配置在web.xml中 7 8 @Override 9 public void destroy() {10 characterEncoding = null;11 }12 13 @Override14 public void doFilter(ServletRequest request, ServletResponse response,15 FilterChain chain) throws IOException, ServletException {16 if (enabled || characterEncoding != null) {17 request.setCharacterEncoding(characterEncoding);18 response.setCharacterEncoding(characterEncoding);19 }20 chain.doFilter(request, response);21 }22 23 @Override24 public void init(FilterConfig config) throws ServletException {25 characterEncoding = config.getInitParameter("characterEncoding");26 enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());27 }28 }
然后自己在web.xml文件中做如下配置
12 13characterEncodingFilter 3training.model.filter.CharacterEncodingFilter 45 8characterEncoding 6UTF-8 79 12enabled 10true 1114 characterEncodingFilter 15/* 16
其实我们可以不必这么麻烦,重复造轮子。
spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题,具体配置如下:
12 9CharacterEncodingFilter 3org.springframework.web.filter.CharacterEncodingFilter 45 8encoding 6utf-8 710 CharacterEncodingFilter 11/* 12
以后我们项目及所有页面的编码均为UTF-8。