package com.yehancheng.filter; 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.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class AccessPurviewFilter extends HttpServlet implements Filter { private String redirectURl = null; public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub /** * doFilter方法的第一个参数为ServletRequest对象。此对象给过滤器提供了对进入的信息(包括 * 表单数据、cookie和HTTP请求头)的完全访问。第二个参数为ServletResponse,通常在简单 * 的过滤器中忽略此参数。最后一个参数为FilterChain,此参数用来调用servlet或JSP页。 -- * 如果处理HTTP请求,并且需要访问诸如getHeader或getCookies等在ServletRequest中 * 无法得到的方法,就要把此request对象构造成HttpServletRequest */ HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; HttpSession session = request.getSession(); // 如果回话中的用户名为空,页面重新定向到登陆页面 if (session.getAttribute("admin") == null) { // 输出为:/DWZModel/admin/operatAdmin.jsp String currentPath = request.getRequestURI(); if (!currentPath.contains("login.jsp")) { // 判断当前页不是登录页 String contextPath = request.getContextPath(); // 输出为:/admin/operatAdmin.jsp String RequestURL = request.getServletPath(); response.sendRedirect(contextPath + redirectURl); } else { // 如果当前是登录页面,则不需要过滤,直接通过 arg2.doFilter(request, response); } } } // 过滤器初始化数据 public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub redirectURl = "/login.jsp"; } }
以下为web.xml中的配置代码:以过滤所有的JSP为例,本来要过滤所有的 .do 文件的,因为前面已经被拦截到struts中处理,所以可以在struts中使用拦截器进行处理
<!-- 配置权限访问过滤器 --> <filter> <filter-name>AccessPurviewFilter</filter-name> <filter-class>com.yehancheng.filter.AccessPurviewFilter</filter-class> </filter> <filter-mapping> <filter-name>AccessPurviewFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>