Posted on 2007-12-05 09:22
陕西BOY 阅读(1180)
评论(1) 编辑 收藏
前段时间很忙,项目比较紧,都没有时间写这个了,今天就写个我在项目中应用的一个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>
好了,大家把上面的代码拷贝到你的项目中,试一下就可以,应该没什么问题,得工作了,今天就到这