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没有。
发布于 2012-10-27 19:29:25
首先,重要的是要了解NullPointerException被抛出的时间和原因。你提出问题的方式表明你不理解它。您问过“为什么抛出NullPointerException?”您没有问“它为什么返回null?”。
正如其javadoc所指示的那样,当您试图访问一个变量或在一个实际为null的对象引用上使用period .操作符调用一个方法时,将抛出NullPointerException。
例如。
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!在您的特定情况下,您试图在null对象上调用方法isNew()。因此这是不可能的。null引用根本没有任何方法。它只是简单地指向什么都没有。您应该改为执行null-check。
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
公共抽象创建( java.lang.Object getSession)
如果create参数为true,则创建(如果需要)并返回与当前请求关联的会话实例。如果create参数为false,则返回与当前请求相关联的任何现有会话实例;如果没有这样的会话,则返回;如果没有这样的会话,则返回。
请看强调的部分。
默认情况下,不带任何参数的HttpServletRequest#getSession()调用使用true作为create参数。另请参阅javadoc
getSession
HttpSession getSession()
返回与此请求关联的当前会话,如果请求没有会话,则创建一个。
请看强调的部分。
我希望您能将此作为一个提示,以便更好地咨询javadoc。它们通常已经包含了您的问题的答案,因为它们非常精确地描述了类和方法的作用。
发布于 2012-10-27 19:07:53
getSession()的默认设置是在没有当前会话的情况下创建一个新会话。
如果没有活动会话,则使用getSession(false)将此行为更改为返回null。
https://stackoverflow.com/questions/13099595
复制相似问题