The following is a question from
Enthuware Mock Exam:
The
correct answer is "It will print Hello and will set the count attribute in the session."
I answered: "It will throw a NullPointerException at request time."
The explanation the tool gives for the correct answer is:
Explanation:
---------------------------
Had this code been in a regular
servlet like this:
It would have thrown an NullPointerException as request.getSession(false) would have returned null (since this is a first ever request to the servlet container.)
However, in case of
JSP pages, the session is automatically created by default. I.e. <%@ page session="true" %>
---------------------------
I wasn't convinced with the explanation and hence I tried creating a JSP and it worked as per the given comments. I also observed the servlet code resulting from translating the JSP (which said HttpSession session = pageCotext.getSession()). For the session attribute of page directive, the spec says:
If true then the implicit script language variable named session of type javax.servlet.http.HttpSession references the current/new session for the page.
But I fail to understand why a JSP is given a session object when it has not been explicitly "requested" by a developer; and what does it mean to have a new session just for the page? And given that, does a request to any JSP automatically associate a session with the client, even when there is no need to have a notion of "state"?
Regards,
Prashant