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;
- }
- }
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;
- }
- }
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接口的实现方式如下:
struts-default.xml配置:
- <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();
- }
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