[Struts2] Action Implements SessionAware

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

1、从ActionContext中获取;

2、实现SessionAware接口。

 

1、从ActionContext中获取:

import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class SessionTestAction extends ActionSupport {
    public String execute() {
     ActionContext actionContext = ActionContext.getContext();
       Map session = actionContext.getSession();
       session.put("USER_NAME", "Test User");
       return SUCCESS;
    }
}

2、实现SessionAware接口:

import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class SessionTest1Action extends ActionSupport implements SessionAware {
    private Map session;
    public void setSession(Map session) {
       this.session = session;
    }
    public String execute() {
       this.session.put("USER_NAME", "Test User 1");
       return SUCCESS;
    }
}
进一步阅读Struts2.1.8.1源码,SessionAware接口的实现方式如下:

<interceptors>
  ...
  <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
  ...
</interceptors>
<interceptor-stack name="defaultStack">
  ...
  <interceptor-ref name="servletConfig"/>
  ...
</interceptor-stack>

打开ServletConfigInterceptor.java源码:

public String intercept(ActionInvocation invocation) throws Exception {
    final Object action = invocation.getAction();
    final ActionContext context = invocation.getInvocationContext();
    
    ...
    if (action instanceof SessionAware) {
        ((SessionAware) action).setSession(context.getSession());
    }
    ...
    return invocation.invoke();
}
即在拦截器处理过程中发现目标Action实现了SessionAware接口,便会调用Action中已经实现的setSession(...)方法,将ActionContext中包装的Session注入目标Action中。目标Action也就可以进一步对Session进行操作了。

来自:http://blog.csdn.net/puffcn/article/details/5607557


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值