Introduction
This tutorial, jsp servlet login logout with remember me, will show you how to login to an application with remember me functionality. Sometimes we need to remember username and password for few days or months or years so that next time onwards a user can login without entering the username and password into the input fields.
The username and password fields get populated automatically from the cookie where the username and password are kept for few days or months or years.
Prerequisites
Eclipse Neon, Java 1.8, Gradle 5.4.1, Apache Tomcat 8.5.39
Final Results
Login Screen
The below login screen has username, password fields where user inputs credentials(roy/roy) for login. A user is given a checkbox with label Remember to opt for remembering user’s credentials so next time when the same user tries to login from the same browser won’t need to provide the credentials.

User Remember
When user inputs username/password as roy/roy and checks Remember option.

Home Screen
The below screen is shown when user logged in successfully.

Logout Screen
When user logged out of home page successfully.

Example
Please follow the below steps to implement the jsp servlet login logout with remember me example.
Related Posts:
Creating Project
Create a gradle based web project in Eclipse. The project name is servlet-login-logout.
Updating Build File
Modify build.gradle file to include the required dependencies for our Servlet based login logout application.
plugins {
id 'java-library'
id 'war'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
providedCompile("javax.servlet:javax.servlet-api:3.1.0")
implementation("javax.servlet:jstl:1.2")
}
Creating Servlets
LoginServlet
Class
Create a LoginServlet
. This servlet handles user request and response. When user submits the form, it checks if user input the username and password otherwise it will show error message as these input fields are required. The servlet also checks if user credentials are correct, if not then displays error message.
When user input credentials for login, this server also checks if the remember me checkbox is checked.
If user checked the check box then it creates cookie object and stores the user credentials for 15 days. So next time when user logs in from the same browser, user will automatically be redirected to the home page for next 15 days.
If you want to change the days then you can modify the code in the below servlet class.
package com.roytuts.servlet.login.logout;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
if (userName != null && userName.trim().length() > 0 && password != null && password.trim().length() > 0) {
System.out.println(userName + ":" + password);
if (userName != null && userName.length() != 0 && userName.equals("roy") && password != null
&& password.length() != 0 && password.equals("roy")) {
if (request.getParameter("remember") != null) {
String remember = request.getParameter("remember");
System.out.println("remember : " + remember);
Cookie cUserName = new Cookie("cookuser", userName.trim());
Cookie cPassword = new Cookie("cookpass", userName.trim());
Cookie cRemember = new Cookie("cookrem", remember.trim());
cUserName.setMaxAge(60 * 60 * 24 * 15);// 15 days
cPassword.setMaxAge(60 * 60 * 24 * 15);
cRemember.setMaxAge(60 * 60 * 24 * 15);
response.addCookie(cUserName);
response.addCookie(cPassword);
response.addCookie(cRemember);
}
HttpSession httpSession = request.getSession();
httpSession.setAttribute("sessuser", userName.trim());
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/home.jsp");
requestDispatcher.forward(request, response);
} else {
System.out.println("Authentication failure.");
request.setAttribute("msg", "Authentication failure.");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
}
} else {
System.out.println("Username and Password are required fields.");
request.setAttribute("msg", "Username and Password are required fields.");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
}
}
}
LogoutServlet
Class
Create a LogoutServlet
servlet. This servlet expires the current session for the logged in user when user clicks on logout action.
Once user successfully logged out from the application, user will be redirected to the login page again.
package com.roytuts.servlet.login.logout;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cUserName = new Cookie("cookuser", null);
Cookie cPassword = new Cookie("cookpass", null);
Cookie cRemember = new Cookie("cookrem", null);
cUserName.setMaxAge(0);
cPassword.setMaxAge(0);
cRemember.setMaxAge(0);
response.addCookie(cUserName);
response.addCookie(cPassword);
response.addCookie(cRemember);
HttpSession httpSession = request.getSession();
httpSession.invalidate();
request.setAttribute("msg", "You have successfully logged out.");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
}
}
Deployment Descriptor
Create deployment descriptor web.xml file unsder src/main/webapp/WEB-INF folder. This web.xml file contains web application deployment configurations.
Notice we don’t have Servlet classes in the below deployment descriptor. We are using Servlet API 3.1 and hence we using annotation based configurations for our Servlet classes.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Servlet Login Logout - Remember Me</display-name>
<!-- session expires in 3 minutes -->
<session-config>
<session-timeout>3</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
Creating Views
Login.jsp File
Create a login form – login.jsp under src/main/webapp folder. This form is displayed with username, password, remember me checkbox and login submit button.
The below login form first checks whether login credentials exist in the cookie. If exists then it will use from the cookie and populates form fields with the value, otherwise form fields become empty and user has to input username/password.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Login</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();
String userName = "", password = "",rememberVal="";
if (cookies != null) {
for (Cookie cookie : cookies) {
if(cookie.getName().equals("cookuser")) {
userName = cookie.getValue();
}
if(cookie.getName().equals("cookpass")){
password = cookie.getValue();
}
if(cookie.getName().equals("cookrem")){
rememberVal = cookie.getValue();
}
}
}
%>
<fieldset style="width: 600px; margin: auto;">
<legend>Login</legend>
<div>
<%=request.getAttribute("msg") != null ? request.getAttribute("msg") : ""%>
<form name="loginForm" method="post"
action="<%=request.getContextPath()%>/login">
<p>
<label>Username</label> <input type="text" name="username"
autocomplete="off" value="<%=userName%>" />
</p>
<p>
<label>Password</label> <input type="password" name="password"
autocomplete="off" value="<%=password%>" />
</p>
<p>
<label>Remember</label> <input type="checkbox" name="remember"
value="1"
<%= "1".equals(rememberVal.trim()) ? "checked=\"checked\"" : "" %> />
</p>
<p>
<input type="submit" name="login" value="Login" />
</p>
</form>
</div>
</fieldset>
</body>
</body>
</html>
home.jsp File
Create a home.jsp file under src/main/webapp folder. This file is shown when user successfully authenticated using the credentials.
This page has only welcome message and logout link.
Building and Deploying into Tomcat
Now deploy the application in Tomcat server. Make sure to build application using cmd prompt by executing command gradle clean build.
Once successfully built, deploy the war from into Tomcat server’s webapp directory.
Start the Tomcat server 8.5.39, your application will be deployed automatically.
Testing the Application
Enter username – roy and password – roy. Check the checbox Remember Me. Now login and logout. Next time your login page opens with auto populated username and password.
Source Code
That’s all. Thanks for reading.
Netbeans doesn’t like this line in the index.jsp file
It says : expected and ) expected. Not much help in the error there.
Not sure if it included the actual line of code I had in there before since I am not seeing it in the preview of my message that is waiting to be approved. So the line I am talking about is the one for the Remember input, the part after the value = 1 where it says “1”.equals(rememberVal.trim()) ? “checked=”checked”” : “”