[英]HttpSession - how to get the session.setAttribute?
I'm creating HttpSession container this way: 我正在以这种方式创建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());
And I have SessionListener which should gives me info about session created: 我有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());
...
}
}
How can I get the username
attribute? 如何获取
username
属性?
If I'm trying it using System.out.println("User name: " + session.getAttribute("username"))
it throws java.lang.NullPointerException
.. 如果我使用
System.out.println("User name: " + session.getAttribute("username"))
尝试它,则会抛出java.lang.NullPointerException
..
The HttpSessionListener
interface is used to monitor when sessions are created and destroyed on the application server. HttpSessionListener
接口用于监视在应用程序服务器上创建和销毁会话的时间。 The HttpSessionEvent.getSession()
returns you a session that is newly created or destroyed (depending if it's called by sessionCreated
/ sessionDestroyed
respectively). HttpSessionEvent.getSession()
返回一个新创建或销毁的会话(取决于它是否分别由sessionCreated
/ sessionDestroyed
调用)。
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");
The session.getAttribute("key")
return a value of java.lang.Object
type if given key is found. 如果找到给定键,则
session.getAttribute("key")
返回java.lang.Object
类型的值。 It returns null otherwise. 否则返回null。
String userName=(String)session.getAttribute("username");
if(userName!=null)
{
System.out.println("User name: " + userName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.