以前,我都是自己编写一个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方式造成的中文乱码问题,具体配置如下:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
按 Ctrl+C 复制代码
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以后我们项目及所有页面的编码均为UTF-8。