[英]HttpSession - how to get the session.setAttribute?
我正在以这种方式创建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
..
HttpSessionListener
接口用于监视在应用程序服务器上创建和销毁会话的时间。 HttpSessionEvent.getSession()
返回一个新创建或销毁的会话(取决于它是否分别由sessionCreated
/ sessionDestroyed
调用)。
如果您想要现有会话,则必须从请求中获取会话。
HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");
如果找到给定键,则session.getAttribute("key")
返回java.lang.Object
类型的值。 否则返回null。
String userName=(String)session.getAttribute("username");
if(userName!=null)
{
System.out.println("User name: " + userName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.