欢迎光临郝学武的blog。
        前段时间很忙,项目比较紧,都没有时间写这个了,今天就写个我在项目中应用的一个Filter,这个过滤器负责把定义的文件夹下的所有页面采用gbk编码格式,并且每个页面都不保留缓存。如此的话就不用在所有的业务类里面处理中文问题,降低了代码冗余,节约了开发时间。下面的这个类就负责这个功能。

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/**
 *@author 郝学武
 *设置字符过滤
 */
public class ActionFilter implements Filter
{
 private String encoding = null;  //定义字符编码,缓存,和Local
 private String cache = null;
 private String forceLocal;

 public void init(FilterConfig filterconfig) throws ServletException    //初始化上面的3个变量,分别从web.xml取得值
 {
  this.encoding = filterconfig.getInitParameter("encoding");
  this.cache = filterconfig.getInitParameter("cache");
        this.forceLocal = filterconfig.getInitParameter("forceLocal");
 }
 
 public void doFilter(ServletRequest servletRequest,
   ServletResponse servletResponse,
   FilterChain filterChain) throws IOException, ServletException    //实现缓存存留,字符过滤---
 {
  HttpServletRequest request = (HttpServletRequest) servletRequest;
  HttpServletResponse response = (HttpServletResponse) servletResponse;
  
  if (this.cache != null && "false".equals(this.cache.toLowerCase()))
  {
    response.setHeader("Cache-Control","no-store");
    response.setHeader("Pragrma","no-cache");
    response.setDateHeader("Expires",0);
  }
  if ((forceLocal == null) || (forceLocal.length() <=0) || (forceLocal.equalsIgnoreCase("no"))) {}
        else {
           
        }
  request.setCharacterEncoding(this.encoding);
  filterChain.doFilter(servletRequest, servletResponse);
  return;
 }

 /*
  * (non-Javadoc)
  *
  * @see javax.servlet.Filter#destroy()
  */
 public void destroy()   //销毁过滤
 {
 // TODO Auto-generated method stub
 }
}
        在web.xml中添加filter
<filter>
  <filter-name>WebFilter</filter-name>
  <filter-class>
   com.cnc.yellow.struts.advertisement.ActionFilter
  </filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>gbk</param-value>
  </init-param>
  <init-param>
   <param-name>cache</param-name>
   <param-value>false</param-value>
  </init-param>
  <init-param>
   <param-name>forceLocal</param-name>
   <param-value>no</param-value>
  </init-param>
 </filter>

<filter-mapping>  
  <filter-name>WebFilter</filter-name>
  <url-pattern>/aaa/*</url-pattern>  //设置作用域为webroot下aaa文件夹下所有页面
 </filter-mapping>
好了,大家把上面的代码拷贝到你的项目中,试一下就可以,应该没什么问题,得工作了,今天就到这

Feedback

# re: 写个简单的关于Filter过滤器应用的例子  回复  更多评论   

2007-12-05 12:33 by cheng
恩,不错,收藏了,以后肯定用得找,呵呵.
楼主有空多多分享你的好东东哦~~~~:)

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


网站导航:
 

posts - 17, comments - 65, trackbacks - 0, articles - 28

Copyright © 陕西BOY