【问题标题】:HttpSession - how to get the session.setAttribute?HttpSession - 如何获取 session.setAttribute?
【发布时间】:2011-11-30 11:49:05
【问题描述】:

我正在以这种方式创建 HttpSession 容器:

@SessionScoped
@ManagedBean(name="userManager")
public class UserManager extends Tools
{
  /* [private variables] */
  ...
  public String login() 
  {
    /* [find user] */
    ...
    FacesContext context = FacesContext.getCurrentInstance();
    session = (HttpSession) context.getExternalContext().getSession(true);
    session.setAttribute("id", user.getID());
    session.setAttribute("username", user.getName());
    ...
    System.out.println("Session id: " + session.getId());

我有 SessionListener,它应该给我有关创建会话的信息:

@WebListener
public class SessionListener implements HttpSessionListener
{
  @Override
  public void sessionCreated(HttpSessionEvent event) {    
    HttpSession session = event.getSession();
    System.out.println("Session id: " + session.getId());
    System.out.println("New session: " + session.isNew());
    ...
  }
}

如何获得username 属性?

如果我使用System.out.println("User name: " + session.getAttribute("username")) 尝试它,它会抛出java.lang.NullPointerException..

【问题讨论】:

  • 所以 session 或 System.out 为空
  • 在 JSF 代码中使用原始 Servlet API 几乎在所有情况下都是代码异味。在这种特殊情况下,为什么不只使用会话范围的托管 bean?
  • 我不明白这个问题...?带有FacesContext 的第一部分代码在会话范围的托管bean 中。我要编辑我的帖子。你能告诉我更多吗?

标签: java jsf jakarta-ee listener


【解决方案1】:

HttpSessionListener 接口用于监控应用服务器上会话的创建和销毁时间。 HttpSessionEvent.getSession() 返回一个新创建或销毁的会话(取决于它是否分别被 sessionCreated/sessionDestroyed 调用)。

如果您想要现有会话,则必须从请求中获取会话。

HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");

【讨论】:

  • 谢谢你,先生,你是对的,从请求中获取会话也帮助了我:-)
  • 它就像 php,但由于某种原因我可以通过这个:S 我的代码就是这样,但无法正常工作。 java.lang.NullPointerException at org.apache.jsp.index_jsp._jspService(index_jsp.java:108) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) HttpSession hs = request.getSession(true) ; long idUser = (long)hs.getAttribute("userid");
  • 如果您说如何创建(请求)对象,这对我非常有用? ---request.getSession(true).
【解决方案2】:

如果找到给定的键,session.getAttribute("key") 将返回 java.lang.Object 类型的值。否则返回 null。

String userName=(String)session.getAttribute("username");

if(userName!=null)
{
  System.out.println("User name: " + userName);
}

【讨论】:

  • 谢谢!它现在不为空,但它返回类似session.UserManager@1a4f43e 的内容。是否可以解码对象以便能够像if (userName.equeals("admin")) {} 一样使用它??
  • @gaffcz - 您确定将“字符串”类型值设置为“用户名”键吗? user.getName() 方法的返回类型是什么?
  • 这个答案的第一行,比官方文档要好。如果找不到该属性,我希望它返回 null,但文档没有告诉我...谢谢
猜你喜欢
  • 2010-11-18
  • 2017-07-02
  • 1970-01-01
  • 2016-10-24
  • 2018-02-15
  • 1970-01-01
  • 2016-09-24
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多