Implementing Automatic Login with Cookies in Java Web Applications

Automatic Login Functionality

This guide explains how to implement a 10-day automatic login feature using cookies in a Java web application.

Login Functionality Implementation

First, ensure the basic login functionality is properly implemented:

  • Successful login redirects to the department list page
  • Failed login redirects to an error page

Frontend Modifications

Add a checkbox to the login page with the option for automatic login:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<html>
<head>
	<title>Login Page</title>
	<style>
		body {
			background-color: #f5f5f5;
			font-family: Arial, sans-serif;
		}

		.container {
			max-width: 400px;
			margin: 0 auto;
			padding: 20px;
			background-color: #ffffff;
			border-radius: 8px;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}

		h2 {
			text-align: center;
			color: #333333;
		}

		.form-group {
			margin-bottom: 15px;
		}

		label {
			display: block;
			margin-bottom: 5px;
			color: #666666;
		}

		input[type="text"],
		input[type="password"] {
			width: 90%;
			padding: 10px;
			border: 1px solid #dddddd;
			border-radius: 4px;
		}

		button[type="submit"] {
			display: block;
			width: 100%;
			padding: 10px;
			background-color: #333333;
			color: #ffffff;
			border: none;
			border-radius: 4px;
			cursor: pointer;
		}

		button[type="submit"]:hover {
			background-color: #222222;
		}
	</style>
</head>
<body>
<br>
<br>
<br>
<div class="container">
	<h2>User Login</h2>
	<form action="<%=request.getContextPath()%>/user/login" method="post">
		
		<div class="form-group">
			<label for="username">Username:</label>
			<input type="text" id="username" name="username" required/>
		</div>

		
		<div class="form-group">
			<label for="password">Password:</label>
			<input type="password" id="password" name="password" required/>
		</div>
		<input type="checkbox" name="remember" value="true">Stay logged in for 10 days
		
		<button type="submit" value="login">Login</button>
	</form>
</div>
</body>
</html>

Backend Servlet Modifications

Modify the login method in the servlet to handle automatic login requests:

protected void processLogin(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
String userId = request.getParameter("username");
String userPass = request.getParameter("password");

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

boolean authenticated = false;

try {
    connection = DatabaseUtil.getConnection();
    String sql = "select * from user_accounts where user_id =? and user_password =? ";
    preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setString(1, userId);
    preparedStatement.setString(2, userPass);

    // This result set contains only one record, no loop needed
    resultSet = preparedStatement.executeQuery();
    if (resultSet.next()) {
        authenticated = true;
    }
} catch (SQLException e) {
    throw new RuntimeException(e);
} finally {
    DatabaseUtil.close(connection, preparedStatement, resultSet);
}

if (authenticated) {
    // Login successful, get session object
    HttpSession session = request.getSession();
    session.setAttribute("userId",userId);

    // Login successful and user selected remember me option
    String rememberMe = request.getParameter("remember");
    if("true".equals(rememberMe)){
        Cookie userCookie = new Cookie("userId",userId);
        Cookie passCookie = new Cookie("userPassword",userPass);  // In production, this should be encrypted

        userCookie.setMaxAge(60*60*24*10);
        passCookie.setMaxAge(60*60*24*10);

        userCookie.setPath(request.getContextPath());
        passCookie.setPath(request.getContextPath());

        response.addCookie(userCookie);
        response.addCookie(passCookie);
    }

    // Redirect to list page
    response.sendRedirect(request.getContextPath() + "/departments/list");
} else {
    // Redirect to error page
    response.sendRedirect(request.getContextPath() + "/login-error.jsp");
}

}

Welcome Page Handling

When users revisit the site, they should either be redirected to the department list or login page:


    welcome
package com.example.webapp.actions;

import com.example.utils.DatabaseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // The cookies array is either null or not empty
        Cookie[] cookies = request.getCookies();
        String userId = null;
        String userPass = null;

        if(cookies != null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if("userId".equals(name)){
                    userId = cookie.getValue();
                }else if("userPassword".equals(name)){
                    userPass = cookie.getValue();
                }
            }
        }

        if(userId !=null && userPass !=null){
            // Verify user credentials
            // Correct credentials, login successful
            // Incorrect, return to login
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            boolean success = false;

            try {
                connection = DatabaseUtil.getConnection();
                String sql = "select * from user_accounts where user_id = ? and user_password = ?";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,userId);
                preparedStatement.setString(2,userPass);
                resultSet=preparedStatement.executeQuery();
                if (resultSet.next()) {
                    success = true;
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                DatabaseUtil.close(connection,preparedStatement,resultSet);
            }

            if(success){
                // Login successful, get session object
                HttpSession session = request.getSession();
                session.setAttribute("userId",userId);

                response.sendRedirect(request.getContextPath()+"/departments/list");
            }else {
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
}

Logout Functionality

private void handleLogout(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{

    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            // Set expiration time to 0 to delete the cookie
            cookie.setMaxAge(0);
            // Set the same path as when the cookie was created
            cookie.setPath(request.getContextPath());
            // Add the modified cookie to the response
            response.addCookie(cookie);
        }
    }

    HttpSession session = request.getSession();
    if(session !=null){
        // Manually invalidate the session
        session.invalidate();
    }
    response.sendRedirect(request.getContextPath());
}

Access Control Modifications

Update the code that originally redirected to the login page to redirect to /welcome instead:

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get session object, only if it exists (no need to create a new one)
    HttpSession session = request.getSession(false);

    if(session != null && session.getAttribute("userId") !=null){
        String servletPath = request.getServletPath();
        if("/departments/list".equals(servletPath)){
            listDepartments(request,response);
        }else if("/departments/delete".equals(servletPath)){
            deleteDepartment(request,response);
        }else if("/departments/detail".equals(servletPath)){
            showDepartmentDetail(request,response);
        }else if("/departments/create".equals(servletPath)){
            saveNewDepartment(request,response);
        }else if("/departments/update".equals(servletPath)){
            modifyDepartment(request,response);
       }
    }else {
        // Redirect to welcome page
        System.out.println("Access denied");
        response.sendRedirect(request.getContextPath()+"/welcome");
    }
}

Tags: java web development Cookies Authentication Session Management

Posted on Tue, 23 Jun 2026 17:56:31 +0000 by rnewman