title: Why is my servlet session not persistent?
body: <p>My servlet is working as expected other than when I close the browser (I am not deleting cookies), the session is lost. How can I save the session indefinitely until I invalidate it or I delete my cookies?</p>
  
  <pre><code>@WebServlet(name="ServletOne", urlPatterns={"/", "/ServletOne"})
  public class ServletOne extends HttpServlet {
      private static final long serialVersionUID = 1L;
  
      public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
          HttpSession session = request.getSession(true);
          String newValue = request.getParameter("newValue");
  
          if (session.isNew()) {
              session = request.getSession(true);
              session.setAttribute("myAttribute", "value");
          }
  
          if (newValue != null)
              session.setAttribute("myAttribute", newValue);
  
          RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
          rd.forward(request, response);
      }
  
      public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
          doGet(request, response);
      }
  }
  </code></pre>
  
  <p>My JSP:</p>
  
  <pre><code>&lt;%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%&gt;
  &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt;
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
  &lt;title&gt;Insert title here&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      val == &lt;c:out value="${myAttribute}"&gt;&lt;/c:out&gt;&lt;br&gt;
      &lt;form action="ServletOne" method="POST"&gt;
          &lt;input type="text" name="newValue" /&gt;
          &lt;input type="submit" /&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>If I close the browser and reopen it, <code>myAttribute</code> is always set to the default "value".</p>