title: Storing username, pasword using cookies/sessions - Java Servlets
body: <p>I am trying to create a registration page using servlets. I have created a basic HTML page which has a form with input for username and password. Now what I need to do is store the information submitted to the form using cookies/sessions. Then on the log-in page, a user must be able to login using the information they provided earlier. <strong>So basically I need to know how to store the username and password.</strong></p>
  
  <p>So if I were register with the username: admin and password 123, and then register with the username: user and password: 12345, I shouldn't be able to login with admin and 12345 or user and 123. Thanks!!</p>
  
  <p><strong>HTML FORM</strong></p>
  
  <pre><code>   &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Registration&lt;/title&gt;
          &lt;meta charset="UTF-8"&gt;
          &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
      &lt;/head&gt;
      &lt;body bgcolor="lightblue"&gt;
  
      &lt;center&gt;
          &lt;h1&gt;&lt;/h1&gt;
          &lt;br&gt;
  
          &lt;hr&gt;
          &lt;br&gt;&lt;br&gt;
          &lt;form action="/Registration" method="get"&gt;
              &lt;h3&gt; Please register to start &lt;/h3&gt;
  Username: &lt;input type="text" name="userName"&gt;
  &lt;br&gt;
  Password: &lt;input type="password" name="password"&gt;
  &lt;br&gt;
  &lt;br&gt;
  &lt;input type="submit" value="Register"&gt;
  &lt;br&gt;&lt;br&gt;
  &lt;/form&gt;
      &lt;/center&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>JAVA SERVLET</strong></p>
  
  <pre><code>protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          processRequest(request, response);
  
           // Create cookies for first and last names.      
        Cookie userName = new Cookie("userName",
                        request.getParameter("userName"));
        Cookie password = new Cookie("password",
                        request.getParameter("password"));
  
         // Set expiry date after 24 Hrs for both the cookies.
        userName.setMaxAge(60*60*24); 
        password.setMaxAge(60*60*24); 
  
        // Add both the cookies in the response header.
        response.addCookie( userName );
        response.addCookie( password );
  </code></pre>