★☆

★☆
posts - 0, comments - 0, trackbacks - 0, articles - 80
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

编写一个编码过滤器

Posted on 2008-08-14 12:55 阅读(249) 评论(0)  编辑  收藏 所属分类: jsp页面乱码方面
编写一个编码过滤器:

在Web.xml配置文件中加入
<filter>
     <filter-name>Character Encoding</filter-name>
     <filter-class>com.bonc.res.CharacterEncodingFilter</filter-class>
     <init-param>
       <param-name>encoding</param-name>
       <param-value>GBK</param-value>
     </init-param>
     <init-param>
       <param-name>enable</param-name>
       <param-value>true</param-value>
     </init-param>
   </filter>


然后写个过滤器

/**
 * 对HttpRequest中的字符集进行编码,解决web请求乱码问题
 *
 * @author william
 *
 */
public class CharacterEncodingFilter implements Filter {
 protected FilterConfig config;
 // 对字符进行的何种编码
 protected String encodingName;
 // 是否允许编码
 protected boolean enable;

 /**
  * 默认构造函数
  */
 public CharacterEncodingFilter() {
  encodingName = "UTF-8";
  enable = false;
 }

 /**
  * Filter销毁的时候调用
  */
 public void destroy() {
 }

 /**
  * filter的入口方法
  *
  * @param reqeust
  *            ServletRequest对象
  * @param resonse
  *            ServletResponse对象
  * @param chain
  *            FilterChain对象
  */
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  if (enable) {
   request.setCharacterEncoding(encodingName);
  }
  chain.doFilter(request, response);

 }

 /**
  * 初始化Filter的时候,该方法被调用
  */
 public void init(FilterConfig config) throws ServletException {
  this.config = config;
  loadConfigParams();
 }

 /**
  * 加载Filter的配置参数,参数在web.xml文件中设置
  */
 private void loadConfigParams() {
  // encoding
  this.encodingName = config.getInitParameter("encoding");
  
  // filter enable flag
  String strIgnoreFlag = config.getInitParameter("enable");
  
  if (strIgnoreFlag.equalsIgnoreCase("true")) {
   this.enable = true;
  } else {
   this.enable = false;
  }
 }

}


只有注册用户登录后才能发表评论。


网站导航: