java

位置:IT落伍者 >> java >> 浏览文章

struts2访问session的两种方法


发布日期:2018年10月18日
 
struts2访问session的两种方法

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进行操作了

               

上一篇:Hibernate持久化技术中多对多关系应用

下一篇:Spring获取Bean的几种方式