In order to detect the creation of a new session you need to implement a HttpSessionListener
Configure it in your web.xml
<listener>
<listener-class>com.my.pack.age.MyHttpSessionListener</listener-class>
</listener>
Or annotated the class with @WebListener if using servlet spec 3.0
When a session is created by the container it fires the method sessionCreated, the next call to isNew()
will return true
.
To answer the question - and just repeat what jCoder said - the session is already created when the JSP is invoked. The servlet container generates a servlet for every JSP, if you look at that code you'll find out that a call of getSession()
already happens there an the session - if not already created - created at this moment. When your servlet then calls the method getSession()
, the session returner is the one created trough the JSP-servlet. Hence it is always returning false
.
Example Servlet code snippet generated by tomcat
response.setContentType("text/html; charset=ISO-8859-15");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession(); // session is created here
out = pageContext.getOut();
_jspx_out = out;
With the actual configuration the block if (session.isNew()){}
will never be executed. If you want to performe some actions when the session is created then either create and configure a session listener or configure your session to ne create a seesion - as suggested by MarkThomas - so that the block if (session.isNew()){}
in your servlet can be executed.