Originally posted by Romy Huang:
Problem
Consider the following JSP code (See exhibit).
What will it print for the very first request to this page as well as the web application that contains this page?
Code
<html><body>
<%
Integer count = (Integer) request.getSession(false).getAttribute("count");
if(count != null )
{
out.println(count);
}
else request.getSession(false).setAttribute("count", new Integer(1));
%>
Hello!
</body></html>
(Select 1 correct option.)
A. It will print Hello!
B. It will print Hello and will set the count attribute in the session.
C. It will throw a NullPointerException at request time.
D. It will not compile.
I will choose C, but the answer is B.
Why?
Hi Romy !
The correct answer is "B".
JSP sessions are configured via 'page' directive and 'session' attribute.
By default sessions are always *enabled*. This is equal if you would have :
in your JSP.
So, when you call 'getAttribute("count")' the session already exists - it was *implicitly* created by container for you. No NullPointerException thrown.
If you put the following code in your JSP :
then you will get a NullPointerException in server's log file and 500 error in browser as you expected.
regards,
MZ