Filter过滤器 请求乱码处理

过滤器的好处:使用了过滤器,无论是Get/Post方式,接收参数时,都不需要再额外的进行转码,过滤器会自动的帮我们办这件事,乱码问题很好的解决了。

一、配置文件方式配置过滤器

创建CharacterEncodingFilter类,实现Filter接口

public class CharacterEncodingFilter implements Filter {

    private String encode = "UTF-8";

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        String encoding = arg0.getInitParameter("encode");
        if (encoding != null) {
            encode = encoding;
        }
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;

        // post方式设置编码格式:
        request.setCharacterEncoding(encode);
        response.setContentType("text/html;charset=" + encode);

        arg2.doFilter(new CharacterEncodingRequest(request), arg1);
    }

    @Override
    public void destroy() {

    }
}

/**
 * 对Get方式传递的请求参数进行编码
 */
class CharacterEncodingRequest extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    public CharacterEncodingRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    /**
     * 对参数重新编码
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (value == null) {
            return null;
        }
        String method = request.getMethod();
        if ("Get".equalsIgnoreCase(method)) {
            try {
                value = new String(value.getBytes("ISO8859-1"),
                        request.getCharacterEncoding());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

}

在web.xml中配置过滤器

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.filter.util.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encode</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

除了配置web.xml还可以通过配置注解:

@WebFilter(initParams = { @WebInitParam(name = "encode", value = "UTF-8") }, urlPatterns = { "/*" })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值