2009年11月11日

package pub.filters;

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;

public class SetCharacterEncodingFliter implements Filter{
 
 protected String encoding = null;
 protected FilterConfig filterConfig = null;
 protected boolean ignore = true;
 
 //设置申请对象的值为空,有利于内存资源的快速释放
 public void destroy() {
  this.encoding = null;
  this.filterConfig = null;
 }
 //Filter的主题操作
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  //判断是否需要进行编码的设置
  if(!ignore||(request.getCharacterEncoding()==null)){
   //得到配置文件的编码类型
   String encoding = selectEncoding(request);
   if(encoding != null)
    request.setCharacterEncoding(encoding);
  }
  chain.doFilter(request, response);
 }
 //初始化方法,通过配置的参数设置标识变量
 public void init(FilterConfig filterConfig) throws ServletException {
  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");
  String value = filterConfig.getInitParameter("ignore");
  if(value == null){
   this.ignore = false;
  }else if(value.equalsIgnoreCase("false")){
   this.ignore = true;
  }else if(value.equalsIgnoreCase("no")){
   this.ignore = true;
  }else{
   this.ignore = false;
  }
 }
 //得到配置的编码类型
 private String selectEncoding(ServletRequest request) {
  // TODO Auto-generated method stub
  return (this.encoding);
 }
}

你可能感兴趣的:(2009年11月11日)