添加EncodingFilter类实现Filter接口

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class EncodingFilter implements Filter {
    FilterConfig config = null;
    // default to GBK
    private String targetEncoding = "GBK";

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        this.targetEncoding = config.getInitParameter("encoding");
    }

    public void destroy() {
        config = null;
        targetEncoding = null;
    }

    public void doFilter(ServletRequest srequest, ServletResponse sresponse,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)srequest;
        request.setCharacterEncoding(targetEncoding);
        chain.doFilter(srequest, sresponse);
    }
}

在配置在web.xml中添加
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>xx.xx.xx.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>useragents</param-name>
            <param-value>Mac</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

posted on 2016-06-13 14:37  小草忄  阅读(535)  评论(0编辑  收藏  举报