本文共 1215 字,大约阅读时间需要 4 分钟。
在Struts2中,Action类可以通过两种方式获取和操作Session:
通过ActionContext类获取Session:
ActionContext类提供了与Session交互的方法。可以通过ActionContext.getContext()获取当前的ActionContext对象,然后调用getSession()方法获取SessionMap对象。通过SessionMap可以对Session进行增删改查操作。实现SessionAware接口:
Action类可以直接实现org.apache.struts2.interceptor.SessionAware接口。通过这种方式,Action类会自动注册到SessionAware的处理器中。即使在单体测试环境下,也可以通过注入SessionMap进行Session操作。示例1:通过ActionContext获取Session
public class SessionTestAction extends ActionSupport { public String execute() { ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); session.put("user", "Test User"); return SUCCESS; }} 示例2:实现SessionAware接口
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", "Test User 1"); return SUCCESS; }} 通过上述两种方式,都可以实现对Session的读写操作。推荐使用第二种方式,因为它更便于单体测试,只需传递一个Map参数即可。
注销Session的方法:
public String logout() throws Exception { ((org.apache.struts2.dispatcher.SessionMap ) this.session).invalidate(); return SUCCESS;} 转载地址:http://rgpfk.baihongyu.com/