使用过滤器解决全栈乱码问题

1、编写过滤器

package com.gxa.filter;

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

public class CharacterEncodingFilter implements Filter {

    //获取接收初始化参数的变量,记住编码
    private String encoding;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        //获取初始化参数,赋给成员变量
        String e = filterConfig.getInitParameter("encoding");

        if (e == null || e.trim().equals("")) {
            encoding = "UTF-8";
        } else {
            encoding = e;
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        //对传递的对象进行向下转型
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //解决请求的乱码
        req.setCharacterEncoding(encoding);
        //解决响应的乱码
        //1)解决字符流的乱码
        req.setCharacterEncoding(encoding);
        res.setContentType("application/json;charset="+encoding);

        //对资源进行放行
        chain.doFilter(request,response);
    }
}

2、配置过滤器

<!--    配置解决全栈乱码问题-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.gxa.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>

 

 

上一篇:手写一个简化版的Tomcat(BIO版本)


下一篇:Java Web(6)—HttpServletResponse的介绍以及使用