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進行操作了
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28436.html