filter之编码过滤器

Filter接口中有三个重要的方法。 (java类要实现的接口)

  • init()方法:初始化参数,在创建Filter时自动调用。当我们需要设置初始化参数的时候,可以写到该方法中。
  • doFilter()方法:拦截到要执行的请求时,doFilter就会执行。
  • destroy()方法:在销毁Filter时自动调用。

 

web.xml配置

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>contentType</param-name>
            <param-value>text/html;charset=UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.ht</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/servlet/ValidJs</url-pattern>
    </filter-mapping>

 

java代码

 

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 编码过滤器, 设置当前系统的编码。
 * 
 * @author crd
 * 
 */
public class EncodingFilter implements Filter {

    private String encoding = "UTF-8";
    private String contentType = "text/html;charset=UTF-8";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse httpresponse, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) httpresponse;
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);

        response.setContentType(contentType);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String _encoding = config.getInitParameter("encoding");
        String _contentType = config.getInitParameter("contentType");
        // String ext=config.getInitParameter("ext");
        if (_encoding != null)
            encoding = _encoding;
        if (_contentType != null)
            contentType = _contentType;

    }

}

 

posted @ 2019-04-09 11:42  爱跳舞的程序员  阅读(195)  评论(0编辑  收藏  举报