struts2中session的生命周期

Struts2session验证支持

首先我来解释下这个题目。Session是伴随网页生命周期的东西。我们一般在session中放入登录信息,这样可以方便做权限验证。

那么struts2session验证支持是怎么做的呢?使用拦截器(希望你了解拦截器并且有拦截器基础,同时会写自定义拦截器)。那么struts2是应该怎么实现拦截器呢?我们来分析下步骤:

1. 我们的session验证,我们需要验证session里面的东西,那么既然是验证session里面的东西,session里面肯定预先放进了一些东西了。我们就是验证这些东西是不是在。通常,session东西的放入,是在登录中,我们放入用户资料进去。

2. 其次,我们在登录后每次操作的时候,都进入session看是否有,如果没有,就直接返回一个定义的错误页面出来。

接下来就是实现了,struts2session验证有非常好的支持。我们使用SessionAware接口以及AuthenticationInterceptor拦截器就可以实现功能。SessionAware是用来控制session的,AuthenticationInterceptor是用来验证的。

1.实现session的添加

Session的放入都是在登录操作的时候完成的,我们一般有2种方法进行session操作,分别是:

l 通过ActionContext class中的方法getSession得到

l Action实现org.apache.struts2.interceptor.SessionAware接口的方式来对session进行操作。

我们先看第一种,他的操作是:

Map session = ActionContext.getContext().getSession();

session.put("user", "auth");

我们就在execute()方法中直接写就O了。这样session就建立完毕。

接下来我们看第二种,实现了SeesionAware接口

? 首先实现接口SeesionAware

? 其次在bean文件中(一般是实现类)声明session属性,如下:

private Map session;

? 接下来,实现方法(SeesionAware接口方法)

public void setSession(Map session) {

// TODO Auto-generated method stub

this.session = session;

}

接下来,我们在execute方法中写出session放入操作session.put(X,O)等就OK了。

问题:选用那个方式实现?

这里推荐通过第二种方式来使用session,原因是便于做单体测试,用第二种方式,只需要构造一个Map就可以对action class进行单体测试了。

在一个项目中可能会有很多action都需要用到session,如果每个action都来实现org.apache.struts2.interceptor.SessionAware这个接口,可能会显得比较麻烦,所以建议作一个抽象的BaseAction类来实现org.apache.struts2.interceptor.SessionAware接口,以后所有的action只要继承这个BaseAction就可以了。

2.实现验证拦截器AuthenticationInterceptor

上面我们已经实现了session的设置,接下来我们要做的是验证:我们写个拦截器类AuthenticationIntecepter.java ,此截拦器用于验证用户是否已经登录,若未登录,跳转到登陆页面 。

public class AuthenticationInterceptor implments Interceptor {  

  public void init();  

  public void destroy();  

    

  //intercept()方法用于验证用户是否已经登录

  public String intercept(ActionInvocation actionInvocation) throws Exception {  

    Map session = actionInvocation.getInvocationContext().getSession();  

    User user = (User)session.get(user);  

    if (user = null) {

      return Action.INPUT;

    } else {  

      System.out.println("User Logined");  

      return actionInvocation.invoke();  

    }  

  }  

}  

如上,我们的AuthenticationIntecepter.java 要实现Interceptor接口,接口中有默认的3个方法 初始化init,销毁方法destroy,以及“业务方法”intercept,我们不用鸟前面2个方法,只用来弄业务方法。Intercept方法我们在里面取出session进行验证,如果是null,就返回input,如果OK,那么就直接使用ActionInvocation .invoke()方法就继续下一步。

接下来我们让这个类成为真正的拦截器,配置struts.xml文件:

...

  

  

    

class="com.vea.AuthenticationInterceptor" />

    

      

      

    

  

  

  

  

  

    /LoginForm.action

    /Error.jsp

  

  

  

    

  

...

我们把类在这里做拦截器声明,然后用拦截器中,先放入自定义的Intercepter,之后再加入到栈中。

之后我们在xml中写action的时候就可以如下写了:

<action name="AddImage">

<result>/ch2/helloworld/ImageUploadForm.jspresult>

<interceptor-ref name="myStack">interceptor-ref>

action>

进行使用。

你可能感兴趣的:(struts2中session的生命周期)