Spring MVC POST中文乱码解决方案
2012-12-26 13:47 Rollen Holt 阅读(48043) 评论(3) 编辑 收藏 举报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 @Override 14 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 @Override 24 public void init(FilterConfig config) throws ServletException { 25 characterEncoding = config.getInitParameter("characterEncoding"); 26 enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim()); 27 } 28 }
然后自己在web.xml文件中做如下配置
1 <filter> 2 <filter-name>characterEncodingFilter</filter-name> 3 <filter-class>training.model.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>characterEncoding</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 <init-param> 9 <param-name>enabled</param-name> 10 <param-value>true</param-value> 11 </init-param> 12 </filter> 13 <filter-mapping> 14 <filter-name>characterEncodingFilter</filter-name> 15 <url-pattern>/*</url-pattern> 16 </filter-mapping>
其实我们可以不必这么麻烦,重复造轮子。
spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题,具体配置如下:
1 <filter> 2 <filter-name>CharacterEncodingFilter</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>utf-8</param-value> 7 </init-param> 8 </filter> 9 <filter-mapping> 10 <filter-name>CharacterEncodingFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 </filter-mapping>
以后我们项目及所有页面的编码均为UTF-8。
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================
![](http://service.t.sina.com.cn/widget/qmd/1882500857/8c17d4b5/1.png)