2011-10-04 101 views
7

我创建一个HttpSession完全容器是这样的:HttpSession - 如何获取session.setAttribute?

@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 ..尝试它

+0

so session或System.out为null –

+0

在JSF代码中使用原始Servlet API几乎在所有情况下都是代码异味。在这种特殊情况下,为什么不使用会话作用域托管bean? – BalusC

+0

我不明白这个问题......?具有'FacesContext'的代码的第一部分在会话范围内的托管bean中。我要编辑我的帖子..你能告诉我更多吗? – gaffcz

回答

10

HttpSessionListener接口用于监视应用程序服务器上何时创建和销毁会话。 HttpSessionEvent.getSession()会返回一个新创建或销毁的会话(具体取决于是否分别由sessionCreated/sessionDestroyed调用)。

如果你想要一个现有的会话,你将不得不从请求中获得会话。

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

谢谢绅士,你是对的,从请求获得的会话也帮助我:-) – gaffcz

+0

它只是像PHP,但由于某种原因,我可以通过这个:SI只是这样我的代码,但还没有工作。显示java.lang.NullPointerException \t在org.apache.jsp.index_jsp._jspService(index_jsp.java:108) \t在org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) HttpSession的HS =请求.getSession(真); long idUser =(long)hs.getAttribute(“userid”); –

1

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

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

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

谢谢!它现在不是空的,但它返回类似'session.UserManager @ 1a4f43e'的东西。是否有可能解码的对象能够使用它像'if(userName.equeals(“admin”)){}'? – gaffcz

+1

@gaffcz - 你确定将“String”类型的值设置为“username”键吗?什么是user.getName()方法的返回类型? – adatapost

+0

对不起,我在下一节课忘了另一个调试:-)它工作 – gaffcz