【发布时间】:2021-03-20 05:46:53
【问题描述】:
如何在多个 Struts 2 动作类中获取存储的会话值?
我确实不想在所有操作中使用SessionAware 接口。
【问题讨论】:
标签: java session struts2 struts
如何在多个 Struts 2 动作类中获取存储的会话值?
我确实不想在所有操作中使用SessionAware 接口。
【问题讨论】:
标签: java session struts2 struts
您有三个选择:
SessionAware。SessionAware 的基本操作类。ActionContext:Map attibutes = ActionContext.getContext().getSession();
记录在 Struts 2 wiki 的 How do we get access to the session 下。
为什么不您想使用SessionAware 并让您的操作更容易测试?
【讨论】:
SessionAware,那么至少您可以使用一个抽象类或您的操作类扩展的接口。它会将SessionMap 注入到您的操作类实例中。其他获取SessionMap或直接HttpSession的方式来自here:
如果你想在会话中添加一些东西,你应该从动作上下文中获取会话映射
Map<String, Object> session = >ActionContext.getContext().getSession(); session.put("username", username); session.put("role", 1);或者直接使用servlet session
HttpSession session = >ServletActionContext.getRequest().getSession(); session.setAttribute("username", username); session.setAttribute("role", 1);但第一种情况更可取,因为它得到了框架的支持。
更多其他选项(您至少还有五个选项):
scopedModelDriven interceptor;scope interceptor;【讨论】: