学会使用过滤器来处理乱码问题

 开发一个过滤器用于改变请求编码。使用请求编码过滤器就可以避免在程序中改变请求编码。

package com.example.task6.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter", urlPatterns = {"/*"}, initParams = {@WebInitParam(name="encoding",value = "UTF-8")})
public class EncodingFilter implements Filter {
    private String encoding;
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding=filterConfig.getInitParameter("encoding");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }
    public void destroy() {

    }
    public String getEncoding() {
        return encoding;
    }
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
}

你可能感兴趣的:(java)