Lab 7: Creating the login feature

Video lesson published on

This page was originally written in Portuguese. Read the original.

Lab overview and objectives

This lab aims to present a basic way to implement a login feature with username and password.

After completing this lab, you should be able to:

  • Make http requests through an HTML form and capture the request data in a Servlet;
  • Create a database table to store the login credentials (username and password);
  • Create a DAO (Data Access Object) class to check the login credentials;
  • Implement an HTML form to capture the login credentials;
  • Implement a Filter that checks whether the user is logged in on every request;

This lab is also available as a video lesson on YouTube

Car Store #09 - Implementando a funcionalidade de login - PARTE 1 · Video in Portuguese.
Car Store #10 - Implementando a funcionalidade de login - PARTE 2 · Video in Portuguese.
Car Store #11 - Implementando a funcionalidade de login - PARTE 3 · Video in Portuguese.

Task 1: Creating the USR (User) table

One of the features of the Car Store system is its administrative area, which only authorized users should access. To make this possible, we need to implement an authentication layer.

1 - Create a new users table. With the application running (tomcat7:run), go to the H2 DB management console at: http://localhost:8080/console

2 - Once in the H2 DB console, log in with the following information:

  • Driver Class: org.h2.Driver
  • JDBC URL: jdbc:h2:~/test
  • User Name: sa
  • Password: sa

3 - After logging in, you can create your second table. You must create a table called USR (we don’t use the name USER because it is a reserved word in the database). To do so, use the following SQL command:

CREATE TABLE USR (ID INT PRIMARY KEY AUTO_INCREMENT, USERNAME VARCHAR(255), PASSWORD VARCHAR(255));

4 - Once the table is created, let’s create our first user manually. To do so, use the following SQL command:

INSERT INTO USR (USERNAME, PASSWORD) VALUES ('your-user', 'your-password')

5 - Review everything you have done so far, to make sure the table was created and the first user was inserted (INSERT) correctly.


Task 2: Creating the Model and DAO classes that retrieve the login credentials

1 - The first step is to create the User class. To do so, in IntelliJ, go to the model package, in the directory carstore/src/main/java/br.com.carstore.model, right-click it, select New / Java Class, type the name User and press ENTER.

Once the User class is created, let’s add two String properties with the private access modifier: username and password.

We need to implement the accessor methods (getters) and an overloaded constructor that receives these two new properties.

The resulting code should look like the following:

package br.com.carstore.model;

public class User {

    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

}

2 - The second step is to create the DAO called UserDao. This class is responsible for querying the database and retrieving the user credentials stored there.

To do so, in IntelliJ, go to the dao package, in the directory carstore/src/main/java/br.com.carstore.dao, right-click it, select New / Java Class, type the name UserDao and press ENTER.

3 - Once the class is created, let’s implement our first method, called verifyCredentials(). This method returns a boolean and receives a User parameter.

It queries the database based on the username the user typed in the Web form.

The code of the initial implementation should look like the following:

package br.com.carstore.dao;

import br.com.carstore.model.User;

public class UserDao {

    public boolean verifyCredentials(User user) {

        return false;

    }

}

4 - Now let’s start implementing our logic. The first part is the SQL script to run. This script queries the database using a parameter typed on screen. If there are records in the database with the given value, they are returned in a resultSet.

The script is the following:

SELECT * FROM USR WHERE USERNAME = ?

The rest of the implementation is similar to all the other methods implemented earlier, so we can copy and paste it. The only difference is a conditional check inside the while block. If there is a registered username in the database equal (equals) to the one typed, the password is checked. If the password is correct, the method returns true. Otherwise, it returns false.

NOTE: Notice that, before returning true, we close the connection (connection.close()). This is very important: the connection only goes back to the connection pool when it is closed. If we forget to close it, each login holds one connection and, when the pool limit is reached (50 connections, as we configured in the previous lab), the whole application stops responding.

The resulting code should look like the following:

package br.com.carstore.dao;

import br.com.carstore.config.ConnectionPoolConfig;
import br.com.carstore.model.User;

import java.sql.*;

public class UserDao {

    public boolean verifyCredentials(User user) {

        String SQL = "SELECT * FROM USR WHERE USERNAME = ?";

        try {

            Connection connection = ConnectionPoolConfig.getConnection();

            PreparedStatement preparedStatement = connection.prepareStatement(SQL);

            preparedStatement.setString(1, user.getUsername());
            ResultSet resultSet = preparedStatement.executeQuery();

            System.out.println("success in select username");

            while (resultSet.next()) {

                String password = resultSet.getString("password");

                if (password.equals(user.getPassword())) {

                    connection.close();

                    return true;

                }

            }

            connection.close();

            return false;

        } catch (Exception e) {

            System.out.println("Error: " + e.getMessage());

            return false;

        }

    }

}

Task 3: Creating the Servlet that captures the login credentials

1 - Now, with the USR table created in the database and the DAO class created, we can implement the Servlet class that receives the HTTP requests with the login information (username and password).

2 - The first step is to create the LoginServlet class. To do so, in IntelliJ, go to the servlet package, in the directory carstore/src/main/java/br.com.carstore.servlet, right-click it, select New / Java Class, type the name LoginServlet and press ENTER.

In this servlet, we will override the doGet and doPost methods.

When the doGet method receives a request, it forwards it to the login.jsp page. We will create this page later.

The doPost method will have a more robust implementation. When it receives a request, it captures (getParameter) the username and password the user typed in the HTML form.

After capturing the data, it creates a new User object, passing the data through the constructor. Then it creates a new UserDao instance and calls the verifyCredentials() method, passing the user object we have just created as a parameter. This call returns a boolean, which is stored in a variable called isValidUser that we will use next.

3 - Check whether the login is valid. With the isValidUser variable, we can do a conditional check (if …). If the boolean is true, the given credentials are valid, so we can start our user’s session. If it is false, the credentials are not valid, so we redirect the user to the login page again with an informative message.

For valid credentials, we add a variable called loggedUser to the session, as in the following code.

req.getSession().setAttribute("loggedUser", username);

Then we redirect the user to our find-all-cars route, as in the following code:

resp.sendRedirect("find-all-cars");

After the whole implementation, the resulting code should look like the following:

package br.com.carstore.servlet;

import br.com.carstore.dao.UserDao;
import br.com.carstore.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("login.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User(username, password);

        boolean isValidUser = new UserDao().verifyCredentials(user);

        if (isValidUser) {

            req.getSession().setAttribute("loggedUser", username);

            resp.sendRedirect("find-all-cars");

        } else {

            req.setAttribute("message", "Invalid credentials!");

            req.getRequestDispatcher("login.jsp").forward(req, resp);

        }

    }

}

Task 4: Creating the Servlet responsible for logout

1 - With the login servlet ready, we should create a servlet responsible for the logout process. It will receive requests on the ("/logout") route.

In IntelliJ, go to the servlet package, in the directory carstore/src/main/java/br.com.carstore.servlet, right-click it, select New / Java Class, type the name LogoutServlet and press ENTER.

In this servlet, we will only override the doGet method.

When the doGet method receives a request, it simply invalidates the session and redirects the user to the login screen again.

2 - The final result should look like the following:

package br.com.carstore.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getSession().invalidate();

        req.setAttribute("message", "Success on logout");

        req.getRequestDispatcher("login.jsp").forward(req, resp);

    }

}

Task 5: Creating the Filter that checks whether the user is authenticated

1 - Our login feature is almost ready. Now we need to implement the Filter that will intercept all requests to check whether the user is authenticated.

To do so, we will create a new package called filter. In IntelliJ, go to the main package, in the directory carstore/src/main/java/br.com.carstore, right-click it, select New / Package, type the name filter and press ENTER.

2 - With the filter package created, let’s create our class, which we will call AuthenticationFilter. To do so, in IntelliJ, right-click the filter package we have just created, select New / Java Class, type the name AuthenticationFilter and press ENTER.

The AuthenticationFilter class must implement the Filter interface from the javax.servlet package. Since we are implementing the Filter interface, we need to override three methods: init(), doFilter() and destroy().

3 - The logic of the doFilter method is relatively simple. For each filtered request, we do a conditional check that verifies whether the user is authenticated. If so, we let the request through unchanged. If not, we redirect the request to the login page again with a message saying the user is not authenticated.

After the whole implementation, the resulting code should look like the following:

package br.com.carstore.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter({"/admin/*", "/create-car", "/delete-car"})
public class AuthenticationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) { }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        if (isUserLoggedIn(httpServletRequest)) {

            chain.doFilter(servletRequest, servletResponse);

        } else {

            servletRequest.setAttribute("message", "User not authenticated!");

            servletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest, servletResponse);

        }

    }

    @Override
    public void destroy() { }

    private boolean isUserLoggedIn(HttpServletRequest httpServletRequest) {

        return httpServletRequest.getSession().getAttribute("loggedUser") != null;

    }

}

4 - Notice that, in our AuthenticationFilter, the @WebFilter annotation defines three patterns: “/admin/*”, “/create-car” and “/delete-car”. This means that all requests to the admin path and to the car create, update and delete operations will be filtered. No other requests will be filtered.

This is because only the administrative area of the system and the operations that change data are protected. The visitor area (the car listing) is not protected, so its requests do not need to be filtered.

NOTE: Hiding the Delete and Update buttons on the page (we will do this in Task 7) is not enough to protect the system. Anyone could send an HTTP request directly to /delete-car without going through the page. That is why the protection must be done on the server, through the filter.

5 - Review everything you have done so far!


Task 6: Creating the HTML page that captures the login credentials

1 - With the login DAO, Servlet and Filter created, it is time to create the login page (jsp).

In IntelliJ, go to the webapp folder, in the directory carstore/src/main/webapp, right-click it, select New / File, type the name login.jsp and press ENTER.

With the login.jsp file created, paste the content below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>

<form action="/login" method="post">

    <span>${requestScope.message}</span>

    <br>

    <label for="username">Username</label>
    <input type="text" id="username" name="username">

    <br>

    <label for="password">Password</label>
    <input type="password" id="password" name="password">

    <button type="submit">Login</button>

</form>

</body>
</html>

This is a simple page with a form, two input fields where the user types the username and password, and a button that submits the request to the /login path.


Task 7: Refactoring the dashboard.jsp page

If all the instructions were followed successfully, the whole login implementation is done. Now we need to refactor our dashboard.jsp and the ListCarServlet servlet.

This refactoring is needed because the create, update and delete operations can only be performed by an authenticated user. Unauthenticated users can only query the registered data. So the delete and update buttons must be hidden when the user is not authenticated.

1 - In IntelliJ, go to the directory carstore/src/main/webapp, open the dashboard.jsp page and replace the original implementation:

<!DOCTYPE html>
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
  <div>
    <h1>Cars</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Actions</th>
        </tr>
        <c:forEach var="car" items="${cars}">
            <tr>
                <td>${car.id}</td>
                <td>${car.name}</td>
                <td>
                    <form action="/delete-car" method="post">
                        <input type="hidden" id="id" name="id" value="${car.id}">
                        <button type="submit">Delete</button>
                        <span> | </span>
                        <a href="index.jsp?id=${car.id}&name=${car.name}">Update</a>
                    </form>
                </td>
            </tr>
        </c:forEach>
    </table>
  </div>
</body>
</html>

With

<!DOCTYPE html>
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
  <div>

    <c:if test="${sessionScope.loggedUser != null}">
        <span>${sessionScope.loggedUser}</span>
        <a href="/logout">Logout</a>
    </c:if>

    <h1>Cars</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <c:if test="${sessionScope.loggedUser != null}">
                <th>Actions</th>
            </c:if>
        </tr>
        <c:forEach var="car" items="${cars}">
            <tr>
                <td>${car.id}</td>
                <td>${car.name}</td>
                <c:if test="${sessionScope.loggedUser != null}">
                    <td>
                        <form action="/delete-car" method="post">
                            <input type="hidden" id="id" name="id" value="${car.id}">
                            <button type="submit">Delete</button>
                            <span> | </span>
                            <a href="index.jsp?id=${car.id}&name=${car.name}">Update</a>
                        </form>
                    </td>
                </c:if>
            </tr>
        </c:forEach>
    </table>
  </div>
</body>
</html>

2 - Notice that we now have conditional checks (<c:if>) around the logout link, the Actions column header and the column with each car’s buttons. These checks use the loggedUser variable we put in the session at login. This variable is not null when the user is authenticated, so the fields inside the conditional checks are rendered in the browser’s DOM (Document Object Model). If the variable is null, the user is not authenticated, so these fields are not rendered.

3 - The last step is to adjust the ListCarServlet class, adding a new mapping to the @WebServlet annotation and fixing the path of the dashboard.jsp page.

To do so, in IntelliJ, go to the servlet package in the directory carstore/src/main/java/br.com.carstore.servlet and open the ListCarServlet.java class.

Change the mapping of the @WebServlet annotation:

FROM

@WebServlet("/find-all-cars")

TO

@WebServlet({"/find-all-cars", "/admin/find-all-cars"})

In the same class, also change the page path in the doGet() method, adding a slash (/) at the beginning:

FROM

req.getRequestDispatcher("dashboard.jsp").forward(req, resp);

TO

req.getRequestDispatcher("/dashboard.jsp").forward(req, resp);

NOTE: Without the slash, the path is relative to the request URL. When the request arrives through /admin/find-all-cars, the server would look for the page at /admin/dashboard.jsp, which does not exist, and the result would be a 404 error. With the slash, the path always starts from the application root.

4 - Review everything you have done so far, making sure all the steps were done.

5 - Save all changes (CTRL + S) and run your application (tomcat7:run).

Open your application at http://localhost:8080 and, without logging in, try to register a car. Notice that, when you click the Save button, the page shown is not the car listing but the login page, with the message User not authenticated!. This is the expected behavior, because the create, update and delete operations can now only be performed by authenticated users. To perform these operations, the credentials must be provided.

You can also open the login page directly at the URL: http://localhost:8080/login

NOTE: Pay attention here: you must type the same credentials (username and password) you inserted in the database (INSERT) in step 4 of Task 1. Otherwise, you will get an invalid username or password message.

After typing the correct credentials, you will be redirected to the dashboard.jsp page, which now shows your user, the Logout link and the delete and update buttons.

If you don’t want to provide the credentials, you can open the dashboard.jsp page directly at the URL: http://localhost:8080/find-all-cars. The page renders correctly, but the delete and update buttons should not appear.


Congratulations! 👍

You implemented the login feature, and the requests to the protected area ("/admin") and to the create, update and delete operations are filtered, checking whether the users are authenticated.