HttpSession - 如何获取session.setAttribute? [英] HttpSession - how to get the session.setAttribute?
问题描述
我正在以这种方式创建HttpSession容器:
I'm creating HttpSession container this way:
@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,它应该给我关于创建会话的信息:
And I have SessionListener which should gives me info about session created:
@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());
...
}
}
我怎样才能得到用户名
属性?
How can I get the username
attribute?
如果我正在尝试使用 System.out.println(用户名:+ session.getAttribute(username))
它抛出 java.lang.NullPointerException
..
If I'm trying it using System.out.println("User name: " + session.getAttribute("username"))
it throws java.lang.NullPointerException
..
推荐答案
HttpSessionListener
接口用于监视在应用程序服务器上创建和销毁会话的时间。 HttpSessionEvent.getSession()
返回一个新创建或销毁的会话(取决于它是否被 sessionCreated
/调用)分别 sessionDestroyed
。
The HttpSessionListener
interface is used to monitor when sessions are created and destroyed on the application server. The HttpSessionEvent.getSession()
returns you a session that is newly created or destroyed (depending if it's called by sessionCreated
/sessionDestroyed
respectively).
如果您想要现有会话,则必须从请求中获取会话。
If you want an existing session, you will have to get the session from the request.
HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");
这篇关于HttpSession - 如何获取session.setAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!