1. Create database table used for authentication
7. Test Login and Logout Functions
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, `fullname` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
package net.codejava; public class User { private int id; private String fullname; private String email; private String password; // getters and setters are not shown for brevity }You should generate getter and setter methods for all fields of this class. They are not shown in the above code or brevity.
package net.codejava; import java.sql.*; public class UserDAO { public User checkLogin(String email, String password) throws SQLException, ClassNotFoundException { String jdbcURL = "jdbc:mysql://localhost:3306/bookshop"; String dbUser = "root"; String dbPassword = "password"; Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword); String sql = "SELECT * FROM users WHERE email = ? and password = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, email); statement.setString(2, password); ResultSet result = statement.executeQuery(); User user = null; if (result.next()) { user = new User(); user.setFullname(result.getString("fullname")); user.setEmail(email); } connection.close(); return user; } }Note that the database connection information specified in the beginning of the checkLogin() method. You should update the JDBC URL, username and password accordingly to MySQL on your computer.You can see checkLogin() method returns a non-null User object if the email and password are found in the database. Otherwise null is returned.To learn more about database programming in Java, read this JDBC tutorial.
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Bookshop Website</title> </head> <body> <div style="text-align: center"> <h1>Admin Login</h1> <form action="login" method="post"> <label for="email">Email:</label> <input name="email" size="30" /> <br><br> <label for="password">Password:</label> <input type="password" name="password" size="30" /> <br>${message} <br><br> <button type="submit">Login</button> </form> </div> </body> </html>When running, this login page looks like this:Note that in the login.jsp page, we use an EL expression ${message} to display the message sent from the server – typically to tell the user that the login failed.If you want to validate the fields in the form before the form is submitted, add the following script tags inside the <head> section of the page:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.0/dist/jquery.validate.min.js"></script>Here we use 2 jQuery libraries (core and validation) from CDN websites.And add the following jQuery code before the closing </html> tag:
<script type="text/javascript"> $(document).ready(function() { $("#loginForm").validate({ rules: { email: { required: true, email: true }, password: "required", }, messages: { email: { required: "Please enter email", email: "Please enter a valid email address" }, password: "Please enter password" } }); }); </script>This script validates the email and password fields are not empty, and the user must enter a valid email address. You can use plain Javascript to validate the form’s fields, but using jQuery is more convenient.
package net.codejava; import java.io.*; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/login") public class UserLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UserLoginServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String password = request.getParameter("password"); UserDAO userDao = new UserDAO(); try { User user = userDao.checkLogin(email, password); String destPage = "login.jsp"; if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user", user); destPage = "home.jsp"; } else { String message = "Invalid email/password"; request.setAttribute("message", message); } RequestDispatcher dispatcher = request.getRequestDispatcher(destPage); dispatcher.forward(request, response); } catch (SQLException | ClassNotFoundException ex) { throw new ServletException(ex); } } }As you can see, the doPost() method handles the request to login from the client. It calls the checkLogin() method of the UserDAO class to verify email and password against the database.If the login succeeds, it sets an attribute in the session to store information about the logged in user, and forwards the request to the admin home page:
if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user", user); destPage = "home.jsp"; }To learn more about session handling in Java, read this Java session tutorial.If the login fails, sets error message as an attribute in the request, and forwards to the login page again:
} else { String message = "Invalid email/password"; request.setAttribute("message", message); }You can learn more about redirection in Java servlet here.And code of the home.jsp page is as follows:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Admin CPanel - Bookshop</title> </head> <body> <div style="text-align: center"> <h1>Welcome to Bookshop Website Admin Panel</h1> <b>${user.fullname} (${user.email})</b> <br><br> <a href="/logout">Logout</a> </div> </body> </html>Note that we use EL expression ${user.fullname} to display the full name and ${user.email} to show the email of the logged in user. And there is a logout link that allows the user to logout from the website.You can learn more about EL operators in JSP by reading this EL operators summary article.
package net.codejava; import java.io.IOException; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/logout") public class UserLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UserLogoutServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute("user"); RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp"); dispatcher.forward(request, response); } } }As you can see, we check if a session exists, remove the attribute user which is set in the login function, and forward the request to the login page.