随笔-211  评论-26  文章-8  trackbacks-0
filter 的用法,的确是比较有扩展性的一种方法...可以通过filter结合读取web.xml中的filter参数来完成一系列的动作,做法如下:

首先,实现javax.servlet.Filter接口,编写一个处理request编码的过滤器类...

package tutorial.struts.filter;

import
javax.servlet.Filter;
import
javax.servlet.FilterConfig;
import
javax.servlet.ServletException;
import
javax.servlet.ServletRequest;

import
javax.servlet.ServletResponse;
import
javax.servlet.FilterChain;
import
java.io.IOException;

public class SetCharacterEncodingFilter implements
Filter {

 
protected
Filter Config filterConfig;
 
protected
String encodingName;
 
protected boolean
enable;

 
public
SetCharacterEncodingFilter() {
   
this
.encodingName = "UTF-8";
   
this .enable = false
;
  }

 
public void init(FilterConfig filterConfig) throws
Servlet Exception {
   
this
.filterConfig = filterConfig;
    loadConfigParams();
  }

 
private void
loadConfigParams() {
   
//encoding

     this .encodingName = this .filterConfig.getInitParameter("encoding");
   
// filter enable flag...

    String strIgnoreFlag = this .filterConfig.getInitParameter("enable");
   
if
(strIgnoreFlag.equalsIgnoreCase("true")) {
     
this .enable = true
;
    }
else
{
     
this .enable = false
;
    }
  }

 
public void
doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain)
throws
IOException, ServletException {
   
if ( this
.enable) {
      request.setCharacterEncoding(
this
.encodingName);
    }
    chain.doFilter(request, response);
  }

 
public void
destroy() {
  }
                
}


然后,需要在web.xml中注册我们的过滤器类:

  < filter >

    < filter -name > Set Character Encoding </< span> filter -name >

    < filter -class > tutorial.struts.filter.SetCharacterEncodingFilter </< span> filter -class >

    < init-param >

      < param-name > encoding </< span> param-name >

      < param-value > UTF-8 </< span> param-value >

    </< span> init-param >

    < init-param >

      < param-name > enable </< span> param-name >

      < param-value > true </< span> param-value >

    </< span> init-param >

  </< span> filter >

  < filter -mapping >

    < filter -name > Set Character Encoding </< span> filter -name >

    < servlet -name > Action Servlet </< span> servlet -name >

  </< span> filter -mapping >

  < filter -mapping >

    < filter -name > Set Character Encoding </< span> filter -name >

    < servlet -name > Faces Servlet </< span> servlet -name >

  </< span> filter -mapping >

posted on 2006-10-03 17:27 dragon 阅读(318) 评论(0)  编辑  收藏 所属分类: jsp mysql 乱码解决方案系列