编码过滤器(utf-8)

web.xml配置



    <filter>
        <filter-name>Utf_8Filterfilter-name>
        <filter-class>com.studentManagement.filter.Utf_8Filterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>Utf_8Filterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

servlet类


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

@WebFilter(filterName = "Utf_8Filter")
public class Utf_8Filter implements Filter {
    private String encoding;
    private HashMap params = new HashMap();

    // 项目结束时就已经进行销毁
    public void destroy() {
        params = null;
        encoding = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
       // response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);
        chain.doFilter(request, response);
    }

    // 项目启动时就已经进行读取
    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("encoding");
        for (Enumeration e = config.getInitParameterNames(); e.hasMoreElements(); ) {
            String name = (String) e.nextElement();
            String value = config.getInitParameter(name);
            params.put(name, value);
        }
    }

}

你可能感兴趣的:(编码过滤器(utf-8))