Struts 的Action中若希望访问Session对象可采用两种方式
从ActionContext中获取
实现SessionAware接口
从ActionContext中获取
import javautilMap;
import comopensymphonyxworkActionContext;
import comopensymphonyxworkActionSupport;
public class SessionTestAction extends ActionSupport {
public String execute() {
ActionContext actionContext = ActionContextgetContext()
Map session = actionContextgetSession()
sessionput(USER_NAME Test User)
return SUCCESS;
}
}
import javautilMap; import comopensymphonyxworkActionContext; import comopensymphonyxworkActionSupport; public class SessionTestAction extends ActionSupport { public String execute() { ActionContext actionContext = ActionContextgetContext() Map session = actionContextgetSession() sessionput(USER_NAME Test User) return SUCCESS; } }
实现SessionAware接口
[java] view plaincopyprint?
import javautilMap;
import orgapachestrutsinterceptorSessionAware;
import comopensymphonyxworkActionSupport;
public class SessionTestAction extends ActionSupport implements SessionAware {
private Map session;
public void setSession(Map session) {
thissession = session;
}
public String execute() {
thissessionput(USER_NAME Test User )
return SUCCESS;
}
}
import javautilMap; import orgapachestrutsinterceptorSessionAware; import comopensymphonyxworkActionSupport; public class SessionTestAction extends ActionSupport implements SessionAware { private Map session; public void setSession(Map session) { thissession = session; } public String execute() { thissessionput(USER_NAME Test User ) return SUCCESS; } }
进一步阅读Struts源码SessionAware接口的实现方式如下
strutsdefaultxml配置
<interceptors>
…
<interceptor name=servletConfig class=orgapachestrutsinterceptorServletConfigInterceptor/>
…
</interceptors>
<interceptorstack name=defaultStack>
…
<interceptorref name=servletConfig/>
…
</interceptorstack>
<interceptors> … <interceptor name=servletConfig class=orgapachestrutsinterceptorServletConfigInterceptor/> … </interceptors> <interceptorstack name=defaultStack> … <interceptorref name=servletConfig/> … </interceptorstack>
打开ServletConfigInterceptorjava源码
public String intercept(ActionInvocation invocation) throws Exception {
final Object action = invocationgetAction()
final ActionContext context = invocationgetInvocationContext()
…
if (action instanceof SessionAware) {
((SessionAware) action)setSession(contextgetSession())
}
…
return invocationinvoke()
}
public String intercept(ActionInvocation invocation) throws Exception { final Object action = invocationgetAction() final ActionContext context = invocationgetInvocationContext() … if (action instanceof SessionAware) { ((SessionAware) action)setSession(contextgetSession()) } … return invocationinvoke() }
即在拦截器处理过程中发现目标Action实现了SessionAware接口便会调用Action中已经实现的setSession(…) 方法将ActionContext中包装的Session注入目标Action中目标Action也就可以进一步对Session进行操作了