Pergunta

I am new to J2EE and stuck in Session Management. According to the specifications, the isNew() method of HttpSession returns true if there is no previously created sessionID from the client stored on the server. I have run the following code and the isNew() method is not returning true even at the first execution. So far I have tried the following things:

  1. Removed my browser's history (everything.. I am using Firefox).
  2. Build and run my web app from Netbeans 7.3.1. In that case, a new Session ID is generated but the isNew() method is surely not returning true.
  3. Restarted the PC(though a stupid one to do).

My question is, what should I do to execute the if (session.isNew()){} block in the servlet code (including any settings with the browser and anything else)? And what is wrong with my code?

Here is my code below..

Code for the initial view:: index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Welcome to color selection page</h1>
        <form method="POST"
              action="NewPattern">
            Select beer characteristics<br>
                Color:
                <select name="color" size="1">
                    <option value="light">light</option>
                    <option value="amber">amber</option>
                    <option value="brown">brown</option>
                </select>
                <br>
                <input type="SUBMIT">
        </form>
    </body>
</html>

Code for the servlet::

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        try {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NewServlet</title>");            
            out.println("</head>");
            out.println("<body>");

            if (session.isNew())
                out.println("It is a new session.  Session ID: " + request.getSession());
            else
                out.println("It is not a new session.  Session ID: " + request.getSession());

            out.println("<h1>Got your chosen color " + request.getParameter("color") + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
        finally {            
            out.close();
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Code for the DD::

<?xml ...>
<web-app ...>
    <servlet>
        <servlet-name>ServletNew</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletNew</servlet-name>
        <url-pattern>/NewPattern</url-pattern>
    </servlet-mapping>
</web-app>
Foi útil?

Solução

The problem is that you first visit index.jsp and then access the servlet.

The server most likely will create the session at the first resource that you access, so the session is new on index.jsp. The servlet is accessed afterwards, so the session is not new there any more.

You can basically test your code by cleaning the session cookies and open the servlet directly in the browser by manually entering its URL.

I also suggest installing the Firefox plugin "Firebug" which has a network console where you can see every request to the server including all data that is transferred. (Another great plugin is "Web Developer Toolbar" which makes it easy to clean just the session cookies.)

Depending on what you are going to achieve, you either need to re-think the page flow or consider using a web framework like Struts.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top