merlin

精益求精

孤鸿

导航

Java中的过滤器

package ittest.merlini.Util;

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.HttpServlet;

public class CharacterEncodingFilter extends HttpServlet implements Filter {

    protected String encoding = null;

    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);

        response.setContentType("text/html;charset=" + encoding);

        chain.doFilter(request, response);

    }

    public void destroy() {

    }

}
View Code

web.xml

<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>ittest.merlini.Util.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>

posted on 2014-02-08 11:24  天地一连线_孤鸿挂飘渺  阅读(183)  评论(0编辑  收藏  举报