java filter基础

web.xml配置信息

 <filter>
    <filter-name>Myfilter</filter-name>
    <filter-class>com.filter.Myfilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>gb2312</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Myfilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
  </filter-mapping>

 

java filter类信息

package com.filter;

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;

/**
 * Servlet Filter implementation class Myfilter
 */
public class Myfilter implements Filter {

    /**
     * Default constructor. 
     */
	protected String encoding=null;
	protected FilterConfig filterConfig=null;
    public Myfilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		this.encoding=null;
		this.filterConfig=null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
          if(encoding!=null)
          {
        	  request.setCharacterEncoding(encoding);
        	  response.setContentType("text/html;charset="+encoding);
          }
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig=fConfig;
		this.encoding=filterConfig.getInitParameter("encoding");
		System.out.print(encoding);
	}

}

  

posted on 2012-12-30 15:22  duhuawei  阅读(177)  评论(0)    收藏  举报