标签:
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.xml中的配置方法
<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的使用可以进行权限的验证,日志的记录等方法
标签:
原文地址:http://www.cnblogs.com/whyd/p/5228634.html