首页 > 代码库 > Spring CharacterEncodingFilter
Spring CharacterEncodingFilter
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项目来说非常简单易用
Spring CharacterEncodingFilter
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。