【问题标题】:Session in Struts 2Struts 2 中的会话
【发布时间】:2012-06-21 00:24:14
【问题描述】:

这是在 Struts2 的会话中存储值的正确方法吗?

Map<String, Object> session = ActionContext.getContext().getSession();
session.put("user", "USERNAME");

【问题讨论】:

  • 你可以这样做,但首选的方式是实现 SessionAware 接口。阅读herehere 了解更多信息。
  • 从 actionContext 获取会话对象不是问题,因为它是在 TheadLocal 上实现的,尽管这不是一个好习惯。
  • SessionAware 绝对是首选;使动作测试更容易。
  • 我和 Dave 在一起,虽然这完全没有问题,但我相信使用 SessionAware 会更勤奋、更灵活

标签: java session struts2


【解决方案1】:

struts 2.x 中的 SessionAware 接口,我们的 Action 类需要实现 SessionAware 接口才能将 HTTP Session 行为引入到我们的 Action 类中。

如果我们从 SessionAware 接口实现,我们需要在我们的动作类中通过 SessionAware 覆盖方法 setSession()。如果我们从 SessionAware 接口实现我们的动作类,那么 struts 2 控制器不会完全注入会话对象,而是会注入具有类似行为的 Map 对象。

 Map m;
 public void setSession(Map m)
    {
        this.m=m;
    }

 public String execute()
    {
        m.put("user", "USERNAME");


        return SUCCESS;
    }

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 2014-01-23
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多