![](/img/trans.png)
[英]HttpSession is null (randomly) when retrieved from HttpServletRequest using ExternalContext
[英]HttpSession is null
A) FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext=facesContext.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(false);
if(session.isNew()) { // java.lang.NullPointerException
B) HttpServletRequest req1 = (HttpServletRequest)FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
HttpSession session1=req1.getSession();
if(session1.isNew()) { // no Exception
为什么情况A抛出NullPointerException而情况B没有。
首先,重要的是要了解何时以及为什么引发NullPointerException
。 您提出问题的方式表示您不理解。 您问“为什么它会引发NullPointerException
?”。 您没有问“为什么它返回null
?”。
正如其javadoc所指示的那样,当您尝试使用period来访问变量或调用方法时,将抛出NullPointerException
.
对象引用上的运算符,该引用实际上为 null
。
例如
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!
在您的特定情况下,您试图在null
对象上调用isNew()
方法。 因此这是不可能的。 null
引用根本没有方法。 它只是一点都没有指向。 您应该改为进行空检查。
HttpSession session = (HttpSession) externalContext.getSession(false);
if (session == null) {
// There's no session been created during current nor previous requests.
}
else if (session.isNew()) {
// The session has been created during the current request.
}
else {
// The session has been created during one of the previous requests.
}
如果尚未创建会话,则带有false
参数的getSession()
调用可以返回null
。 另请参阅javadoc :
getSession
public abstract java.lang.Object getSession(boolean create)
如果
create
参数为true
,请创建(如有必要)并返回与当前请求关联的会话实例。 如果create
参数为false
返回与当前请求关联的任何现有会话实例, 如果没有此类会话 ,则返回null
。
参见重点部分。
HttpServletRequest#getSession()
调用不接受任何参数,默认情况下使用true
作为create
参数。 另请参阅javadoc :
getSession
HttpSession getSession()
返回与此请求关联的当前会话, 或者如果该请求没有会话,则创建一个 。
参见重点部分。
希望您以此为指导更好地参考javadocs。 由于它们非常准确地描述了类和方法的作用,因此它们所包含的问题解答通常已经很多。
如果没有当前会话,则getSession()的默认值是创建一个新的会话。
如果没有活动会话,则使用getSession(false)可以将此行为更改为返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.