spring filter拦截器

南笙酒味 提交于 2020-03-31 00:30:37

实现的功能:判断用户是否已登录,未登录用户禁止访问任何页面或action,自动跳转到登录页面。
比较好的做法是不管什么人都不能直接访问jsp页面,要访问就通过action,这样就变成了一个实实在在的权限控制了。
那么就有3种方法可以解决楼主的问题
1,直接使用filter
2,直接使用webwork的interceptor,
3,将action交给spring管理,使用spring的Aop机制

让用户可以直接访问jsp本来就违反了mvc的本意了
1 直接使用filter
web.xml配置

<filter>  
        <filter-name>SecurityServlet</filter-name>  
        <filter-class>com.*.web.servlet.SecurityServlet</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>SecurityServlet</filter-name>  
        <url-pattern>*.jsp</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>SecurityServlet</filter-name>  
        <url-pattern>*.do</url-pattern>  
    </filter-mapping>


SecurityServlet 类

package com.*.web.servlet;

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 SecurityServlet extends HttpServlet implements Filter {
    private static final long serialVersionUID = 1L;

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
             HttpServletRequest request=(HttpServletRequest)arg0;  
           HttpServletResponse response  =(HttpServletResponse) arg1;    
           HttpSession session = request.getSession(true);    
           String usercode = (String) request.getRemoteUser();// 登录人
           String user_role = (String)session.getAttribute("role");//登录人角色
           String url=request.getRequestURI();  
           if(usercode==null || "".equals(usercode) || user_role == null || "".equals(user_role)) {      
                //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转  
                if(url!=null && !url.equals("") && ( url.indexOf("Login")<0 && url.indexOf("login")<0 )) {  
                    response.sendRedirect(request.getContextPath() + "/login.jsp");  
                    return ;  
                }              
            }  
            arg2.doFilter(arg0, arg1);  
            return;  
    }
    public void init(FilterConfig arg0) throws ServletException {
    }

}
配置中的filter-mapping,定义的是需过滤的请求类型,上面的配置即过滤所有对jsp页面和action的请求。过滤器的实现与struts2、spring框架无关,在用户请求被相应前执行,在过滤器中,可使用response.sendRedirect("")等方法

跳转到需要的链接,如登录页面、错误页面等,不需要跳转时,arg2.doFilter(arg0, arg1);即可继续执行用户的请求。注意使用filter时避免连续两次跳转,否则会报java.lang.IllegalStateException错误,具体配置方法网上有,除非必要,不建议使用/*(过滤所有访问)的配置方式,这样配置,图片、js文件、css文件等访问都会被过滤


2 Spring拦截

Spring配置

<bean id="springSessionInterceptor" class="com.*.web.servlet.SpringLoginInterceptor" >
     </bean>
<bean id="autoPorxyFactoryBean1"
        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="interceptorNames">
            <list>
                <value>springLoginInterceptor</value>
            </list>
        </property>
        <property name="beanNames" >
        <list>
            <value>*Controller</value>
            </list>
        </property>
    </bean>
SpringLoginInterceptor实现类

package com.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMapping;

public class SpringLoginInterceptor implements MethodInterceptor {
    private static final Logger log = Logger
    .getLogger(SpringLoginInterceptor .class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        log.info("拦截开始!");
        Object[] args = invocation.getArguments();  
        HttpServletRequest request = null;
        HttpServletResponse response = null;
        ActionMapping  mapping = null;
        for (int i = 0 ; i < args.length ; i++ )    {
          if (args[i] instanceof HttpServletRequest) request = (HttpServletRequest)args[i];  
          if (args[i] instanceof HttpServletResponse) response = (HttpServletResponse)args[i];  
          if (args[i] instanceof ActionMapping) mapping = (ActionMapping)args[i];  
        }
        if (request != null && mapping != null) {
            String url=request.getRequestURI();  
            HttpSession session = request.getSession(true);    
            String usercode = (String) request.getRemoteUser();// 登录人
            String user_role = (String)session.getAttribute("user_role");//登录人角色
            
            if (usercode == null || usercode.equals("")) {
                if ( url.indexOf("Login")<0 && url.indexOf("login")<0 ) {
                    
                    return mapping.findForward("loginInterceptor");
                }  
                return invocation.proceed();
            }
            else {
                return invocation.proceed();
            }
        }
        else {
            return invocation.proceed();
        }
    }
}
//================================================================
在 SPRING 3 MVC 模式下,还可以如下实现:
public class SecurityFilter extends HandlerInterceptorAdapter  {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==>>Begin to Filter session====");
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        System.out.println("===??Current User=="+user);
        String curPath=request.getRequestURL().toString();
        System.out.println("===>> curpath:"+curPath);
        if (curPath.indexOf("GPS/User/Index")>=0){
            return true;
        }
        if(null==user || "".equals(user)){
            return true;
            /**
             * handle session and security if you want.
             */
            //request.getRequestDispatcher("/index.jsp").forward(request, response);
        }        
        return super.preHandle(request, response, handler);
    }
    
    

}
在 name-servlet.xml spring 的配置文件中注明:
<bean id="urlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >
        <property name="interceptors">  
           <list>  
               <bean class="com.ibm.tds.filter.SecurityFilter"/>  
           </list>  
        </property>
    </bean>

就可以用了。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!