[Struts2] Action Implements SessionAware

本文介绍了在Struts2框架中如何通过两种方式访问Session对象:一种是从ActionContext中获取,另一种是实现SessionAware接口。此外,还深入解析了SessionAware接口的具体实现原理。

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

1、从ActionContext中获取;

2、实现SessionAware接口。

 

1、从ActionContext中获取:

  1. import java.util.Map;  
  2. import com.opensymphony.xwork2.ActionContext;  
  3. import com.opensymphony.xwork2.ActionSupport;  
  4. public class SessionTestAction extends ActionSupport {  
  5.     public String execute() {  
  6.      ActionContext actionContext = ActionContext.getContext();  
  7.        Map session = actionContext.getSession();  
  8.        session.put("USER_NAME""Test User");  
  9.        return SUCCESS;  
  10.     }  
  11. }  

 

2、实现SessionAware接口:

[java]  view plain copy
  1. import java.util.Map;  
  2. import org.apache.struts2.interceptor.SessionAware;  
  3. import com.opensymphony.xwork2.ActionSupport;  
  4. public class SessionTest1Action extends ActionSupport implements SessionAware {  
  5.     private Map session;  
  6.     public void setSession(Map session) {  
  7.        this.session = session;  
  8.     }  
  9.     public String execute() {  
  10.        this.session.put("USER_NAME""Test User 1");  
  11.        return SUCCESS;  
  12.     }  
  13. }  
 

 

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

 

struts-default.xml配置:

[xhtml]  view plain copy
  1. <interceptors>  
  2.   ...  
  3.   <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>  
  4.   ...  
  5. </interceptors>  
  6. <interceptor-stack name="defaultStack">  
  7.   ...  
  8.   <interceptor-ref name="servletConfig"/>  
  9.   ...  
  10. </interceptor-stack>  
 

 

打开ServletConfigInterceptor.java源码:

[java]  view plain copy
  1. public String intercept(ActionInvocation invocation) throws Exception {  
  2.     final Object action = invocation.getAction();  
  3.     final ActionContext context = invocation.getInvocationContext();  
  4.       
  5.     ...  
  6.     if (action instanceof SessionAware) {  
  7.         ((SessionAware) action).setSession(context.getSession());  
  8.     }  
  9.     ...  
  10.     return invocation.invoke();  
  11. }  
 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值