How To Code Login and Logout With Java Servlet, JSP and MySQL
How To Code Login and Logout With Java Servlet, JSP and MySQL
How To Code Login and Logout With Java Servlet, JSP and MySQL
MySQL
Written by Nam Ha Minh
Last Updated on 04 July 2019 | Print M Email
In this tutorial, I will guide you how to implement login and logout functions for a small Java web application using Servlet, JSP, JDBC
and MySQL. Just plain old, core Java EE technologies. No frameworks are used.
Suppose that you have an existing Java web project and now you wish to add the login and logout features for your website.
Table of content:
Make sure that the table you use for authentication has at least 3 fields: fullname, email and password.
Here’s the structure of the table users I use for this tutorial:
If you haven’t created any table for authentication, execute the following MySQL script to create one:
/
Of course you can add additional fields to this table if you want.
1 package net.codejava;
2
3 public class User {
4 private int id;
5 private String fullname;
6 private String email;
7 private String password;
8
9 // getters and setters are not shown for brevity
10
11 }
You should generate getter and setter methods for all fields of this class. They are not shown in the above code or brevity.
/
1 package net.codejava;
2
3 import java.sql.*;
4
5 public class UserDAO {
6
7 public User checkLogin(String email, String password) throws SQLException,
8 ClassNotFoundException {
9 String jdbcURL = "jdbc:mysql://localhost:3306/bookshop";
10 String dbUser = "root";
11 String dbPassword = "password";
12
13 Class.forName("com.mysql.jdbc.Driver");
14 Connection connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);
15 String sql = "SELECT * FROM users WHERE email = ? and password = ?";
16 PreparedStatement statement = connection.prepareStatement(sql);
17 statement.setString(1, email);
18 statement.setString(2, password);
19
20 ResultSet result = statement.executeQuery();
21
22 User user = null;
23
24 if (result.next()) {
25 user = new User();
26 user.setFullname(result.getString("fullname"));
27 user.setEmail(email);
28 }
29
30 connection.close();
31
32 return user;
33 }
34 }
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.
/
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:
1 <script
2 src="https://code.jquery.com/jquery-3.4.1.min.js"
3 integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
4 crossorigin="anonymous"></script>
5 <script type="text/javascript"
6 src="https://cdn.jsdelivr.net/npm/[email protected]/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:
1 <script type="text/javascript">
2
3 $(document).ready(function() {
4 $("#loginForm").validate({
5 rules: {
6 email: {
7 required: true,
8 email: true
9 },
10
11 password: "required",
12 },
13
14 messages: {
15 email: {
16 required: "Please enter email",
17 email: "Please enter a valid email address"
18 },
19
20 password: "Please enter password"
21 }
22 });
23
24 });
25 </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.
/
1 package net.codejava;
2
3 import java.io.*;
4 import java.sql.SQLException;
5
6 import javax.servlet.*;
7 import javax.servlet.annotation.WebServlet;
8 import javax.servlet.http.*;
9
10 @WebServlet("/login")
11 public class UserLoginServlet extends HttpServlet {
12 private static final long serialVersionUID = 1L;
13
14 public UserLoginServlet() {
15 super();
16 }
17
18 protected void doPost(HttpServletRequest request, HttpServletResponse response)
19 throws ServletException, IOException {
20 String email = request.getParameter("email");
21 String password = request.getParameter("password");
22
23 UserDAO userDao = new UserDAO();
24
25 try {
26 User user = userDao.checkLogin(email, password);
27 String destPage = "login.jsp";
28
29 if (user != null) {
30 HttpSession session = request.getSession();
31 session.setAttribute("user", user);
32 destPage = "home.jsp";
33 } else {
34 String message = "Invalid email/password";
35 request.setAttribute("message", message);
36 }
37
38 RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
39 dispatcher.forward(request, response);
40
41 } catch (SQLException | ClassNotFoundException ex) {
42 throw new ServletException(ex);
43 }
44 }
45 }
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:
1 if (user != null) {
2 HttpSession session = request.getSession();
3 session.setAttribute("user", user);
4 destPage = "home.jsp";
5 }
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:
1 } else {
2 String message = "Invalid email/password";
3 request.setAttribute("message", message);
4 }
/
1 <%@ page language="java" contentType="text/html; charset=utf-8"
2 pageEncoding="utf-8"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="utf-8">
7 <title>Admin CPanel - Bookshop</title>
8 </head>
9 <body>
10 <div style="text-align: center">
11 <h1>Welcome to Bookshop Website Admin Panel</h1>
12 <b>${user.fullname} (${user.email})</b>
13 <br><br>
14 <a href="/logout">Logout</a>
15 </div>
16 </body>
17 </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.
1 package net.codejava;
2
3 import java.io.IOException;
4
5 import javax.servlet.*;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.*;
8
9 @WebServlet("/logout")
10 public class UserLogoutServlet extends HttpServlet {
11 private static final long serialVersionUID = 1L;
12
13 public UserLogoutServlet() {
14 super();
15 }
16
17 protected void doGet(HttpServletRequest request, HttpServletResponse response)
18 throws ServletException, IOException {
19 HttpSession session = request.getSession(false);
20 if (session != null) {
21 session.removeAttribute("user");
22
23 RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
24 dispatcher.forward(request, response);
25 }
26 }
27 }
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.
Now let’s enter correct email and password and click Login, you will see the admin home page appears as follows:
You can see the full name and email of the logged in user are displayed on this page.
Click the Logout link and you will see it redirects to the login page.
That’s how to implement the login and logout functions for a Java web application using Java Servlet, JSP, JDBC and MySQL. It’s very
simple so you can easily add to your existing small project, without using any frameworks.
However, to fully secure login-required pages of a website, you need to implement an authentication filter.
/
By the way, I have a video course that teaches you how to build a complete Java web application (e-commerce). You can learn here.
Attachments:
LoginLogoutServletJSP.zip [Java Login Logout Sample Project] 20 kB