web项目使用spring时,可以使用Spring提供的字符集过滤filter,非常方便对于有中文的字符设置
<!-- 设置请求编码格式为UTF-8 --> <filter> <filter-name>springEncoding</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter>
需要设置的两个参数为encoding、forceEncoding,分别设置字符集,及是否设置字符集,该filter也非常简单
public class CharacterEncodingFilter extends OncePerRequestFilter { public CharacterEncodingFilter() { forceEncoding = false; } public void setEncoding(String encoding) { this.encoding = encoding; } public void setForceEncoding(boolean forceEncoding) { this.forceEncoding = forceEncoding; } protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if(encoding != null && (forceEncoding || request.getCharacterEncoding() == null)) { request.setCharacterEncoding(encoding); if(forceEncoding) response.setCharacterEncoding(encoding); } filterChain.doFilter(request, response); } private String encoding; private boolean forceEncoding; }
主要流程即判断是否需要设置字符集,及设置什么字符集。对于web项目来说非常简单易用