在struts2的action中,如何获取session

下面的文字是从struts2官网拷过来的,英文好点的可以看看
How do we get access to the session

You can obtain the session attributes by asking the ActionContext or implementing SessionAware. Implementing SessionAware is preferred.

Ask the ActionContext
The session attributes are available on the ActionContext instance, which is made available via ThreadLocal.

Map attibutes = ActionContext.getContext().getSession();

Implement SessionAware
_Preferred_

Ensure that servlet-config Interceptor is included in the Action's stack.
//The default stack already includes servlet-config.
Edit the Action so that it implements the SessionAware interface.
The SessionAware interface expects a setSession method. You may wish to include a companion getSession method.
At runtime, call getSession to obtain a Map representing the session attributes.
Any changes made to the session Map are reflected in the actual HttpSessionRequest. You may insert and remove session attributes as needed.


Map parameters = this.getSession();

When the servlet-config Interceptor sees that an Action implements ParameterAware, it passes a Map of the session attributes to the Action's setParameters method. Changes made to the Map are reflected in the runtime HttpSessionRequest.

To unit test a SessionAware Action, create your own Map with the pertinent session attributes and call setSession as part of the test's setUp method.

注意执行顺序:
先由 servlet-config Interceptor 调用 Action的 setParameters方法,传值。


官网地址:
http://struts.apache.org/2.0.14/docs/how-do-we-get-access-to-the-session.html

你可能感兴趣的:(struts2,session,action)