S2SH项目登陆拦截的回顾(补)

   之前学三大框架的时候也没怎么做总结,这次回顾就把总结写一下。

   搭建好S2SH的框架后,在web-INF下建立对应对应的文件夹里边放着不能由URL直接访问的那些页面。在WEB-INF下的页面都是不能直接访问的。同时,CSS和JS还有图片的文件夹和WEB-INF所在的文件夹是同级的。

   在这样的情况下,除了登陆的login.jsp能被url访问外,其他的页面都需要通过action来进行跳转控制。那么现在就需要对未登录的非法action请求进行控制。通过struts2的拦截器来实现。实现如下:

<interceptors>
         <interceptor name="loginJudge" class="com.rbac.interceptor.UsrLoginInterceptor">
         </interceptor>    
         <!-- 自定义拦截器栈-->
       <interceptor-stack name="myDefaultStack">
       <interceptor-ref name="loginJudge">
           </interceptor-ref>
       <interceptor-ref name="defaultStack">
          </interceptor-ref>

       </interceptor-stack>
</interceptors>

               <!-- 将自定义拦截器栈设置默认的拦截器 -->
         <default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
<global-results>
     <result name="login" type="redirect">/login.jsp</result>
</global-results>
      

  写一个拦截器:

 1 package com.rbac.interceptor;
 2 
 3 import java.util.Map;
 4 
 5 import com.opensymphony.xwork2.Action;
 6 import com.opensymphony.xwork2.ActionInvocation;
 7 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
 8 import com.rbac.action.LoginAction;
 9 
10 public class UsrLoginInterceptor extends AbstractInterceptor{
11     
12     //先判断用户是否登陆,如果还没有登陆,若没有登陆则为非法请求,进行拦截。
13     @Override
14     public String intercept(ActionInvocation arg0) throws Exception {
15         //判断请求是否为登陆的请求,如果是登陆请求则不拦截。
16         if(LoginAction.class==arg0.getAction().getClass())
17         {
18             return arg0.invoke();
19         }
20         //如果是其他action的请求,进行拦截
21         Map map =
22                arg0.getInvocationContext().getSession();
23         if(null==map.get("username"))
24         {
25             return Action.LOGIN;
26         }
27 
28         return arg0.invoke();
29     }
30     
31 
32 }

在loginAction中的execute方法中,验证成功后把用户名写到session中:

public String execute() throws Exception {
        String hql="from Master where name=? and password=?";
         Map map = ActionContext.getContext().getSession();
        if(    hibernateTemplate.find(hql, new String[]{username,password}).size()==0)
        {
            return LOGIN;
        }else{
            map.put("username", username);
            return SUCCESS;
        }
        

    }

这样就完成了所有的步骤。当然了,这只是个实验而已~具体的程序还在不断地修修补补中。

<interceptors>
         <interceptor name="loginJudge" class="com.rbac.interceptor.UsrLoginInterceptor">
         </interceptor>
         
         <!-- 自定义拦截器栈-->
       <interceptor-stack name="myDefaultStack">

       <interceptor-ref name="loginJudge">
          </interceptor-ref>
       <interceptor-ref name="defaultStack">
          </interceptor-ref>
 
       </interceptor-stack>
</interceptors> 
原文地址:https://www.cnblogs.com/terryheihei/p/3214921.html