标题:Struts2的Action访问Session对象的两种方式及原理


Struts2的Action中若希望访问Session对象,可采用两种方式:

1、从ActionContext中获取;

2、实现SessionAware接口。

1、从ActionContext中获取:

importjava.util.Map;

importcom.opensymphony.xwork2.ActionContext;

importcom.opensymphony.xwork2.ActionSupport;

publicclassSessionTestActionextendsActionSupport{

publicStringexecute(){

ActionContextactionContext=ActionContext.getContext()//先获得ActionContext实例

Mapsession=actionContext.getSession();

session.put("USER_NAME","TestUser");

returnSUCCESS;

}

}

importjava.util.Map;importcom.opensymphony.xwork2.ActionContext;importcom.opensymphony.xwork2.ActionSupport;publicclassSessionTestActionextendsActionSupport{publicStringexecute(){ActionContextactionContext=ActionContext.getContext();Mapsession=actionContext.getSession();session.put("USER_NAME","TestUser");returnSUCCESS;}}

2、实现SessionAware接口:

[java]viewplaincopyprint?

importjava.util.Map;

importorg.apache.struts2.interceptor.SessionAware;

importcom.opensymphony.xwork2.ActionSupport;

publicclassSessionTest1ActionextendsActionSupportimplementsSessionAware{

privateMapsession;

publicvoidsetSession(Mapsession){

this.session=session;

}

publicStringexecute(){

this.session.put("USER_NAME","TestUser1");

returnSUCCESS;

}

}

importjava.util.Map;importorg.apache.struts2.interceptor.SessionAware;
importcom.opensymphony.xwork2.ActionSupport;
publicclassSessionTest1ActionextendsActionSupportimplementsSessionAware{
privateMapsession;
publicvoidsetSession(Mapsession){
this.session=session;
}
publicStringexecute(){
this.session.put("USER_NAME","TestUser1");
returnSUCCESS;
}
}

进一步阅读Struts2.1.8.1源码,SessionAware接口的实现方式如下:

struts-default.xml配置:

<interceptors>

<interceptorname="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>

</interceptors>

<interceptor-stackname="defaultStack">

<interceptor-refname="servletConfig"/>

</interceptor-stack>

<interceptors>…<interceptorname="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
…</interceptors><interceptor-stackname="defaultStack">…<interceptor-refname="servletConfig"/>…</interceptor-stack>

打开ServletConfigInterceptor.java源码:

publicStringintercept(ActionInvocationinvocation)throwsException{

finalObjectaction=invocation.getAction();

finalActionContextcontext=invocation.getInvocationContext();

if(actioninstanceofSessionAware){

((SessionAware)action)。setSession(context.getSession());

}

returninvocation.invoke();

}

publicStringintercept(ActionInvocationinvocation)throwsException{finalObjectaction=invocation.getAction();
finalActionContextcontext=invocation.getInvocationContext();…if(actioninstanceofSessionAware){
((SessionAware)action)。setSession(context.getSession());}…returninvocation.invoke();}

即在拦截器处理过程中发现目标Action实现了SessionAware接口,便会调用Action中已经实现的setSession(…)方法,
将ActionContext中包装的Session注入目标Action中。目标Action也就可以进一步对Session进行操作了。

文章来源:http://java.chinaitlab.com/Struts/896689.html