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 <init-param>
9 <param-name>forceEncoding</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>
通过源码可以看到在web.xml配置CharacterEncodingFilter 时,可以配置两个参数:encoding和forceEncoding ;
encoding:编码格式;
forceEncoding :是否允许设置的encoding 覆盖request和response中已经存在的encodings。
- public class CharacterEncodingFilter extends OncePerRequestFilter {
- private String encoding;
- private boolean forceEncoding = false;
- /**
- * Set the encoding to use for requests. This encoding will be passed into a
- * {@link javax.servlet.http.HttpServletRequest#setCharacterEncoding} call.
- * <p>Whether this encoding will override existing request encodings
- * (and whether it will be applied as default response encoding as well)
- * depends on the {@link #setForceEncoding "forceEncoding"} flag.
- */
- public void setEncoding(String encoding) {
- this.encoding = encoding;
- }
- /**
- * Set whether the configured {@link #setEncoding encoding} of this filter
- * is supposed to override existing request and response encodings.
- * <p>Default is "false", i.e. do not modify the encoding if
- * {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
- * returns a non-null value. Switch this to "true" to enforce the specified
- * encoding in any case, applying it as default response encoding as well.
- * <p>Note that the response encoding will only be set on Servlet 2.4+
- * containers, since Servlet 2.3 did not provide a facility for setting
- * a default response encoding.
- */
- public void setForceEncoding(boolean forceEncoding) {
- this.forceEncoding = forceEncoding;
- }
- @Override
- protected void doFilterInternal(
- HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException {
- if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
- request.setCharacterEncoding(this.encoding);
- if (this.forceEncoding) {
- response.setCharacterEncoding(this.encoding);
- }
- }
- filterChain.doFilter(request, response);
- }
- }