Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Servlets with tomcat Implement the \"Remember Me\" checkbox in the doPost o

ID: 3586102 • Letter: J

Question

Java Servlets with tomcat

Implement the "Remember Me" checkbox in the doPost of the LoginSessions.java file provided (marked in the comments). Other files are provided for functionality.

For the "Remember Me" checkbox, upon login with the checkbox ticked, the program should create a cookie called 'student' that stores the student's id (you can see how this works in the Student.java class file). When a student visits the login page, the program should check for the 'student' cookie and, if it is there, you should automatically redirect the student to the student's profile instead of the login page. Upon clicking logout, the 'student' cookie should be destroyed.

LoginSessions.java

package studentLogin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import studentLogin.Student;

@WebServlet(urlPatterns="/sessions/Login", loadOnStartup=3)
public class LoginSessions extends HttpServlet {
   private static final long serialVersionUID = 1L;

   public void init(ServletConfig config) throws ServletException {
       super.init(config);
      
       // Create a few students
       ArrayList<Student> students = new ArrayList<Student>();
       students.add(new Student("John", "Doe", "john@doe.com", "abcd"));
       students.add(new Student("Mary", "Jane", "mary@jane.com", "efgh"));
       students.add(new Student("Joe", "Boxer", "joe@boxer.com", "ijkl"));
       // Add the students to the application scope (Servlet Context)
       getServletContext().setAttribute("students", students);
   }
  
  
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // Set the content type
       response.setContentType("text/html");
       // Get a reference to the PrintWriter that lets us talk to the client
       PrintWriter out = response.getWriter();
      
       // Generate the HTML
       out.println("<!DOCTYPE html>");
       out.println("<html lang="en">");
       out.println("<head>");
       out.println("    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">");
       out.println("    <meta charset="UTF-8">");
      
       /* Page Title goes here */
       out.println("    <title>Login (Sessions)</title>");
       out.println("</head>");
      
       /* Page Body goes here */
       out.println("<body>");
       out.println("<div class="container">");
      
       out.println("<div class="page-header">");
       out.println("    <h1>Login <small>HttpSessions</small></h1>");
       out.println("</div>");
      
       // Display the error message if it exists
       String error = (String) request.getAttribute("error");
      
       if (error != null)
       out.println("<p class="text-center text-danger">" + error + "</p>");
      
       // Create the login form
       out.println("<form action="Login" method="post">");
       out.println("   <div class="form-group">");
       out.println("       <label>Username (E-mail Address)</label>");
       out.println("       <input class="form-control"type="text" name="username" placeholder="Email">");
       out.println("   </div>");
       out.println("   <div class="form-group">");
       out.println("       <label>Password</label>");
       out.println("       <input class="form-control"type="password" name="password" placeholder="Password">");
       out.println("   </div>");
       out.println("   <div class="checkbox">");
       out.println("       <label>");
       out.println("           <input type="checkbox" name="rememberMe" id='checkThis'> Remember Username");
       out.println("       </label>");
       out.println("   </div>");
       out.println("   <button type="submit" class="btn btn-primary">Login</button>");
       out.println("</form>");
      
       out.println("</div>");
       out.println("</body>");
      
       out.println("</html>");
   }

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // Get the credentials from the request object
       String username = request.getParameter("username");
       String password = request.getParameter("password");
      
       // If the user submitted bad input, just redisplay the form
       if (username == null || username.trim().length() == 0 ||
           password == null || password.trim().length() == 0) {
          
           doGet(request, response);
          
           // Don't forget, calling `doGet` does not stop the execution of this method.
           // We need to `return`.
           return;
       }
      
       // If we get here then the Student submitted a username and password.
      
       // Do something with the "Remember Me" checkbox
       // To do...
       // if (request.getParameter("rememberMe").equals("on"))
    //make cookie,etc

    //else continue like normal
      
       // Authenticate the Student by searching all of the Students in our app
       // and comparing the submitted credentials against each student's email and password
       ArrayList<Student> students = (ArrayList<Student>) getServletContext().getAttribute("students");
      
       for (Student student : students) {
           if (student.getEmail().toLowerCase().equals(username.trim().toLowerCase()) &&
               student.getPassword().equals(password)) {
               // If we get here, the username and password match the current `student`.
               // Let's create a session attribute that references `this current student`.
               HttpSession session = request.getSession();
               session.setAttribute("authenticatedStudent", student);
              
               // Now that we've set an attribute in the session scope, let's
               // redirect the Student to the "Student's Profile" area.
               response.sendRedirect("MyProfile");
               return;              
           }
       }
      
       // if we get here then we couldn't find a Student that matched the submitted credentials
       // So, we add an error message to the request scope and redisplay the form
       request.setAttribute("error", "Invalid username and/or password");
       doGet(request, response);
   }

}

StudentProfile.java

package studentLogin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import studentLogin.Student;

/**
* Servlet implementation class StudentProfile
*/
@WebServlet("/sessions/MyProfile")
public class StudentProfile extends HttpServlet {
   private static final long serialVersionUID = 1L;

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
       // Let's get a reference to the student who is currently logged in
       Student student = (Student) request.getSession().getAttribute("authenticatedStudent");
      
       // If there is no student logged in, redirect back to the login page
       if (student == null) {
           response.sendRedirect("Login");
           return;
       }
      
       // Set the content type
       response.setContentType("text/html");
      
       // Get a reference to the PrintWriter that lets us talk to the client
       PrintWriter out = response.getWriter();
      
       // Generate the HTML
       out.println("<!DOCTYPE html>");
       out.println("<html lang="en">");
       out.println("<head>");
       out.println("    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">");
       out.println("    <meta charset="UTF-8">");
      
       /* Page Title goes here */
       out.println("    <title>Student Profile</title>");
       out.println("</head>");
      
       /* Page Body goes here */
       out.println("<body>");
       out.println("<div class="container">");
      
       out.println("<div class="jumbotron">");
       out.println("    <h1>" + student.getFirstName() + "'s Profile</small></h1>");
       out.println("    <p class="lead">This is a Student's Only area.</p>");
       out.println("   <a class="btn btn-primary" href="Logout">Logout</a>");
       out.println("</div>");
      
       out.println("<h3>Grades <small>" + student.getFullName() + "</small></h3>");
       out.println("<table class="table table-bordered table-striped table-hover">");
       out.println("   <tr>");
       out.println("       <th>Assignment</th>");
       out.println("       <th>Score</th>");      
       out.println("   </tr>");
              
       // Print all of the student's scores.
       double[] scores = student.getScores();
       for (int i = 0; i < scores.length; i++) {
           out.println("   <tr>");
           out.println("       <td>Assignment " + (i+1) + "</td>");
           out.println("       <td>" + scores[i] + "</td>");
           out.println("   </tr>");
       }
      
       out.println("</table>");
      
       out.println("</div>");
       out.println("</body>");
      
       out.println("</html>");
      

   }


  
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // TODO Auto-generated method stub
       doGet(request, response);
   }

}

LogoutSessions.java

package studentLogin;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/sessions/Logout")
public class LogoutSessions extends HttpServlet {
   private static final long serialVersionUID = 1L;
  
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.getSession().invalidate();
       response.sendRedirect("Login");
   }

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request, response);
   }

}

Student.java

package studentLogin;

public class Student {

   static int count = 0;
   static final int NUMBER_OF_ASSIGNMENTS = 5;
  
   int id;  
   String firstName, lastName;  
   String email;
   String password;
  
   double[] scores = new double[NUMBER_OF_ASSIGNMENTS];
  
   public Student(String firstName, String lastName, String email, String password) {
      
       this.id = count++;
      
       this.firstName = firstName;
       this.lastName = lastName;
       this.email = email;
       this.password = password;
      
       // Randomly assign scores to this student;
       for (int i = 0; i < NUMBER_OF_ASSIGNMENTS; i++)
           scores[i] = Math.random() * 100;
              
   }

   public String getFullName() {
       return firstName + " " + lastName;
   }
   public String getFirstName() {
       return firstName;
   }

   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }

   public String getLastName() {
       return lastName;
   }

   public void setLastName(String lastName) {
       this.lastName = lastName;
   }

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email;
   }

   public String getPassword() {
       return password;
   }
  
   public void setPassword(String password) {
       this.password = password;
   }

   public double[] getScores() {
       return scores;
   }

   public void setScores(double[] scores) {
       this.scores = scores;
   }

   public int getId() {
       return id;
   }
      
  
  
}

Explanation / Answer

Create an empty cookie in the place of comment "//make cookie,etc" in LoginSessions.java like this

Cookie student = new Cookie();

After this when student is verified and username and password matched set the cookie name and value by replacing "// If we get here, the username and password match the current `student`." in LoginSessions.java
student.setName("id");

student.setValue(student.getId());

response.addCookie(student); //adding cookie to response

To destroy cookie in LogoutSession.java

Cookie student = new Cookie("id",""); // this changes value of the cookie with name "id" to "" which means it deletes the cookie

student.setMaxAge(0); //changes max age to 0 seconds which means it will no longer be available

response.addCookie(student);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote