最简单使用的配置登录拦截器(过滤器)的方法,可集成于大部分框架中首先创建loginfilter类 继承httpservlet 实现Filter接口 注意是javax.servlet包下的filter
package com.fiss.controller;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.aop.MethodBeforeAdvice;
import com.fiss.entity.Admin;
public class filter extends HttpServlet implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession(true);
String url = request.getRequestURI();
Admin admin = (Admin) session.getAttribute("admin");
if (admin == null && url.indexOf("login.jsp") == -1
&& !url.equals("/fiss/") && !url.equals("/fiss/admin.do")) {
String location = "/manager/login.jsp";
request.getRequestDispatcher(location).forward(request, response);
System.out.println("成功拦截到外星人企图入侵网站后台 : " + url);
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig arg0) throws ServletException {
}
}
写好以后在web.xml中配置拦截器
<filter>
<filter-name>loginFilter</filter-name>
//这里的filterclass是你创建的fitler类
<filter-class>com.fiss.controller.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
//定义规则
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
配置完成 启动服务器没有报错 尝试直接访问url页面 控制台成功输出拦截信息 OK