title: How to check in servlet that is an user new with session?
body: <p>I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two <code>.jsp</code> file. first one called <code>index.jsp</code>, and another one is <code>selection.jsp</code>. And there is a servlet called <code>controller</code>. At first the <code>index.jsp</code> will be called, and user will be submit a input. That will be redirect in servlet <code>controller</code>. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work. </p>
  
  <p>I am checking whether it is new request or not by <code>session.isNew()</code> method. But it always says it is not new session. <strong>But, if I disable the browser cookies option then it is working fine.</strong> Now what is my observation is that when in the first I request the <code>index.jsp</code> to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book <code>Servlet and JSP</code>.
  <a href="https://i.stack.imgur.com/e9kNY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9kNY.png" alt="enter image description here"></a></p>
  
  <p>Here is my servlet code - </p>
  
  <pre><code>public class Controller extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String user;
      HttpSession session = request.getSession(false);
      if (session == null) {
          user = request.getParameter("user");
          if (user == null) {
              response.sendRedirect("index.jsp");
          }
          session.setAttribute("username", user);
          SelectItem selectItem = new SelectItem();
          selectItem.setUser(user);
          response.sendRedirect("selection.jsp");
          session.setAttribute("selectItem", selectItem);
  
      } else {
          String selectionItem = request.getParameter("selection");
          SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
          if (selectItem != null) {
              selectItem.add(selectionItem);
              session.setAttribute("selectItem", selectItem);
          }
          response.sendRedirect("selection.jsp");
      }
  
  }
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  }
  }
  </code></pre>
  
  <p>So, how to determine whether it is a new session or old one? Thank you.</p>