spring框架的编码过滤器——CharacterEncodingFilter

<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>
@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);
}
 
两个重要参数,分别是encodingforceEncoding
 
/**
 * 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;
}

 

 

posted @ 2015-09-11 10:32  feifeithink  阅读(454)  评论(0)    收藏  举报