现在的位置: 首页 > 综合 > 正文

servlet/jsp中过滤器的运用

2013年08月13日 ⁄ 综合 ⁄ 共 2738字 ⁄ 字号 评论关闭

过滤器是一个对象,可以传输请求或修改响应。它可以在请求到达Servlet/JSP之前对其进行预处理,而且能够在响应离开Servlet/JSP之后对其进行后处理。所以如果你有几个Servlet/JSP需要执行同样的数据转换或页面处理的话,你就可以写一个过滤器类,然后在部署描述文件(web.xml)中把该过滤器与对应的Servlet/JSP联系起来。

你可以一个过滤器以作用于一个或一组servlet,零个或多个过滤器能过滤一个或多个servlet。一个过滤器实现java.servlet.Filter接口并定义它的三个方法:

1. void init(FilterConfig config) throws ServletException:在过滤器执行service前被调用,以设置过滤器的配置对象。

2. void destroy();在过滤器执行service后被调用。

3. Void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException;执行实际的过滤工作。

服务器调用一次init(FilterConfig)以为服务准备过滤器,然后在请求需要使用过滤器的任何时候调用doFilter()。FilterConfig接口检索过滤器名、初始化参数以及活动的servlet上下文。服务器调用destory()以指出过滤器已结束服务。

在doFilter()方法中,每个过滤器都接受当前的请求和响应,而FilterChain包含的过滤器则仍然必须被处理。doFilter()方法中,过滤器可以对请求和响应做它想做的一切。(就如我将在后面讨论的那样,通过调用他们的方法收集数据,或者给对象添加新的行为。)

chain.doFilter()将控制权传送给下一个过滤器。当这个调用返回后,过滤器可以在它的doFilter()方法的最后对响应做些其他的工作;例如,它能记录响应的信息。如果过滤器想要终止请求的处理或或得对响应的完全控制,则他可以不调用下一个过滤器。

以下是一个过滤器的例子,用于获取当前WEB应用的真实路径,因为程序中经常需要知道这个路径,所以这里可以以过虑器的方式获得,放入一个session中,然后程序其他地方就能够使用了。

package wasingmon.common;

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.HttpSession;

public class AppContextFilter implements Filter{
 private FilterConfig config=null;
 public void init(FilterConfig config) throws ServletException {
  this.config=config; 
 }
 public void doFilter(ServletRequest requestx, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)requestx;
  HttpSession session=request.getSession();
  AppContext appcontext=(AppContext)session.getAttribute("wasingmon.common.AppContext");
  if(appcontext==null){
  AppContext context=new AppContext();
  String webRealPath=request.getSession().getServletContext().getRealPath("/");
  if(webRealPath.endsWith("//"))
   context.setWebRealPath(webRealPath);
  else
   context.setWebRealPath(webRealPath+"//");
  session.setAttribute("wasingmon.common.AppContext",context);
  }
  chain.doFilter(request,response);
  
 }
 public void destroy() {
  this.config=null;
 }

}

其中AppContext存放上下问有关信息;

package wasingmon.common;

public class AppContext {
 
 private String webRealPath=null;

 public String getWebRealPath() {
  return webRealPath;
 }

 public void setWebRealPath(String webRealPath) {
  this.webRealPath = webRealPath;
 }

}
在web.xml中,用 <filter>标签部署它:

 <filter>
  <filter-name>AppContext</filter-name>
  <display-name>Appcontext</display-name>
  <filter-class>wasingmon.common.AppContextFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>AppContext</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
这样就完成了过滤器的设置,以后访问jsp/servlet时过滤器就会执行。

END!

抱歉!评论已关闭.