[Java教程]JSP Filter用法
0 2016-02-29 20:00:07 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.
logs
com.filter.LogFilter
loginpage
/login.jsp
logs
/*
说明:filter.doFilter调用是用来区分拦截的前后的doFilter的使用可以进行权限的验证,日志的记录等方法 本文网址:http://www.shaoqun.com/a/197393.html
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。
JS
0