Web.xml里的字符编码过滤器

字符编码过滤器,拦截器自上而下执行,最先指定编码为utf-8。

代码如下:

<filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
    init-param>
    <init-param>
    
        <param-name>forceEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>

这个是指定编码方式。

CharacterEncodingFilter这个过滤器里有encoding和forceRequestEncoding两个变量,其中forceRequestEncoding默认为false,我们再看他的拦截方法。

protected void doFilterInternal(
    HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {

    String encoding = getEncoding();
    if (encoding != null) {
        if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(encoding);
        }
        if (isForceResponseEncoding()) {
            response.setCharacterEncoding(encoding);
        }
    }
    filterChain.doFilter(request, response);
}

当encodeing不为空,设置请求url为utf-8.其中参数的值在web.xml中UTF-8设置。

你可能感兴趣的:(源码随笔)