1

如何在多个 Struts 2 动作类中获取存储的会话值?

不想在所有操作中都使用SessionAware界面。

4

2 回答 2

4

你有三个选择:

  1. 做对并使用SessionAware.
  2. 做正确的事并使用一个使用SessionAware.
  3. 做错了并使用ActionContext
Map attibutes = ActionContext.getContext().getSession();

记录在 Struts 2 wiki 下的How do we get access to the session下。

为什么您不想使用SessionAware并使您的操作更容易测试呢?

于 2013-06-14T16:20:46.393 回答
0

如果您不想SessionAware在多个类中使用,那么至少您可以使用一个抽象类或您的操作类扩展的接口。它将SessionMap向您的操作类实例注入一个。

其他获取SessionMap或直接获取的方法HttpSession来自这里

如果你想在会话中添加一些东西,你应该从操作上下文中获取会话映射

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);

但是第一种情况更可取,因为它得到了框架的支持。


更多其他选项(您至少还有另外五个选项):

于 2013-06-15T16:45:16.333 回答