Search

ID Verification using JSP

0 views

Designing a Secure Login System with JSP

When a web site grows beyond a static set of pages, protecting sensitive areas becomes a top priority. A straightforward approach that still delivers solid security is to keep the authentication logic on the server side and to use a lightweight database that can be managed locally. In this example we’ll use the Java Server Pages (JSP) technology that runs inside a servlet container such as Apache Tomcat, and an MS Access database that stores usernames and passwords in a simple table. The workflow is deliberately minimal: a user submits credentials via a form, the server checks those credentials against the database, and the server redirects the user to either a success page or a retry page. All of this can be achieved with a handful of files and a modest amount of Java code.

Begin by creating a new web application in Tomcat. The folder structure for a standard project looks like this: webapps/YourAppName/WEB-INF. Inside the root of the project you will place your JSP files. For the login interface, create a file called login.jsp. Open the file in a text editor and insert the following markup. It contains a simple HTML form that posts the entered username and password to a second JSP that will handle the authentication.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Please Log In</h1>
<form action="authenticate.jsp" method="post">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Next, set up the database that will hold the credentials. With MS Access you can create a new database file, for example users.accdb, and define a table called Registration. The table should contain at least two fields: Username (Text, primary key) and Password (Text). Once the table is created, add a few test rows. A common practice during development is to keep the passwords in plain text, but remember that in production you should hash them with a secure algorithm such as PBKDF2 or bcrypt. If you want to connect to the database from Tomcat, register an ODBC data source for the Access file via the Windows Control Panel’s ODBC Data Source Administrator. Give the data source a name such as AccessUsers and point it to the users.accdb file. Tomcat can then access the database through the JDBC‑ODBC bridge that ships with the JDK.

The authentication logic lives in a file called authenticate.jsp. This file must establish a JDBC connection, retrieve the submitted username and password from the request, and compare those values to the rows in the Registration table. A small JavaBean called UserAuthenticator will encapsulate the database access so that the JSP remains tidy. Create a package named com.example.auth and inside it a class UserAuthenticator.java with the following code.

package com.example.auth;
import java.sql.*;
public class UserAuthenticator {
  private String dbUrl = "jdbc:odbc:AccessUsers";
  public boolean validate(String user, String pass) throws SQLException {
    Connection con = DriverManager.getConnection(dbUrl);
    String sql = "SELECT Password FROM Registration WHERE Username = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setString(1, user);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
      String stored = rs.getString("Password");
      con.close();
      return stored.equals(pass);
    }
    con.close();
    return false;
  }
}

Compile this class and drop the resulting UserAuthenticator.class into the WEB-INF/classes/com/example/auth directory. The JSP engine will be able to load the bean when the page is executed. In authenticate.jsp write the following code to wire everything together.



String user = request.getParameter("user");
String pass = request.getParameter("pass");
boolean ok = false;
try {
  UserAuthenticator ua = new UserAuthenticator();
  ok = ua.validate(user, pass);
} catch (SQLException e) {
  e.printStackTrace();
}
if (ok) {
  response.sendRedirect("success.jsp");
} else {
  response.sendRedirect("retry.jsp");
}
%>

Two additional JSP files are required to complete the flow. success.jsp simply informs the user that they are logged in, while retry.jsp tells them the login failed and offers another attempt. Here are the minimal contents for each file.

<!-- success.jsp -->
<h1>Welcome, !</h1>
<p>You have successfully accessed the protected area.</p>

<!-- retry.jsp -->
<h1>Login Failed</h1>
<p>The username or password you entered is incorrect. Please try again.</p>
<a href="login.jsp">Back to Login</a>

With the files in place, the login system is ready for deployment. The design keeps the business logic in a separate bean, which makes the JSPs easy to read and maintain. By using a lightweight Access database and a JDBC bridge, the entire application stays portable and simple to set up on any machine that runs Tomcat and the JDK. The next section will walk through the steps required to launch the application, verify that it works, and point out areas where the basic implementation can be expanded for production use.

Bringing It All Together: Deployment and Testing

Deploying a JSP-based application in Tomcat is straightforward because the server automatically scans the webapps directory for applications. After copying the login.jsp, authenticate.jsp, success.jsp, retry.jsp, and the WEB-INF/classes folder into a new folder such as webapps/AuthDemo, simply start the Tomcat service. If you are running Tomcat from the command line, navigate to its bin directory and execute startup.bat (Windows) or startup.sh (Linux). Once the server has started, open a browser and navigate to http://localhost:8080/AuthDemo/login.jsp. The login form should appear.

To test the authentication mechanism, enter a username and password that you added to the Access database earlier. For example, if the table contains a row with Username: nouman and Password: ceab, type those values into the form and press the login button. If the credentials match, the browser will be redirected to success.jsp and you should see a personalized welcome message. If you mistype either the username or the password, the server will route you to retry.jsp, which encourages you to try again. This simple flow demonstrates the core functionality and provides a clear path for further enhancement.

At this stage, you have a fully operational login system that uses JSP for the front end and a JavaBean for database access. While the current implementation is functional, real-world applications typically demand additional security layers. First, replace the plain-text password comparison with hashing. Libraries such as BCrypt can be added to the project’s lib directory and called from UserAuthenticator. Second, implement session handling so that authenticated users can maintain state across pages. In the authenticate.jsp file, after a successful validation, call HttpSession session = request.getSession(); and store the username in the session before redirecting. Finally, consider using a dedicated JDBC driver for Access or migrating to a more robust database like PostgreSQL or MySQL; this will eliminate the dependency on the JDBC‑ODBC bridge, which has been deprecated in newer Java releases.

Another useful enhancement is to guard protected pages against direct URL access. Add a small snippet to the top of any JSP that should be restricted. The snippet checks whether the session contains a valid user attribute and redirects to the login page if not.

HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
  response.sendRedirect("login.jsp");
  return;
}
%>

By integrating these improvements, you can turn the basic demonstration into a secure, maintainable authentication system suitable for production. The architecture remains clear: the front end stays in JSP, the business logic in JavaBeans, and the database is accessed through JDBC. This separation of concerns simplifies debugging, testing, and future scaling. Deploy the updated application again, confirm that session handling works, and you’ll have a solid foundation for any web project that requires user verification.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles