你的位置:首页 > Java教程

[Java教程]JSP Filter用法


1.filter的作用
  • 在HttpServletRequest请求到达Servlet之前,拦截客户的HttpServletRequest
  • 根据需要检查HttpServletRequest的相关信息,修改头信息和数据
  • 在HttpServletResponse到达客户端之前可以进行拦截
  • 在HttpServletResponse到达客户端之前可以进行检查,也可以修改头信息和数据

2.实现方式
  • 定义一个类,继承自javax.servlet.Filter类
  • 实现javax.servlet.Filter的init(),destroy(),doFilter()方法
  • 配置filter在web.

3.具体实现
package com.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LogFilter implements Filter {

private FilterConfig config;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config=filterConfig;
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ServletContext context=config.getServletContext();
long time= System.currentTimeMillis();
System.out.println("过滤开始");
System.out.println(time);
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpSession session=request.getSession(true);
String loginpage=config.getInitParameter("loginpage");
if(session.getAttribute("username")==null&&!request.getContextPath().endsWith(loginpage)){
servletRequest.getRequestDispatcher(loginpage).forward(servletRequest,servletResponse);
}else{
System.out.println(request.getContextPath());
filterChain.doFilter(servletRequest,servletResponse);
long atime= System.currentTimeMillis();
System.out.println(time);
System.out.println("过滤结束");
System.out.println("请求被处理时间是:"+request.getContextPath()+"("+(atime-time)+")");
}

}

@Override
public void destroy() {
config=null;
}
}
4.在web.
<filter>
<filter-name>logs</filter-name>
<filter-class>com.filter.LogFilter</filter-class>
<init-param>
<param-name>loginpage</param-name>
<param-value>/login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>logs</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
说明:filter.doFilter调用是用来区分拦截的前后的
doFilter的使用可以进行权限的验证,日志的记录等方法