JSP - Servlets: Full Login Example

In this section we are going to discuss the implementation of a complete Login application (We received the source code of this application through Amira Thabet)

The application will

  • Ask the user to input his "username" and "password"
  • Check the existence of this user in the Data Base
    • If exists, Retrieve his first name and last name from the DB and display them
    • If not registered, Display "Sorry, you are not registered"
You are assumed to know about the connection between java and DB.

This Login application uses the so called "JavaBeans" and "DAOs" - standing for Data Access Objects - to handle the interactions with the DB.

Beans are normal java classes containing

  1. Attributes
  2. Getters and Setters for such attributes (and may be some additional methods)

In our application, Beans are used to save data needed in the application (in the form of variables) . This data may be a representation of data existing in the DB, data entered by the user, or results of business logic.

DAOs are objects responsible for handling the interactions with the Data Source, through implementing the access mechanism required to work with the data source.

In our application the DAO is responsible for

  1. Reading data from the Bean (data entered by the user) and checking its consistency with the DB - use Getters to get values of variables from the bean-
  2. Retrieving data from the DB and saving it to the Bean - use Setter methods to set values to variables -

You can either go to the Next page to step by step implement the example, or download its source code from here. The source code is commented in details, so that can understand every statement's role.

As mentioned in the application description, the user will have to enter his username and password, so first of all, we need a JSP that asks the user to input his username and password in their corresponding fields.

To have this JSP, please follow these steps:

  • Open eclipse
  • Create a new "Dynamic Web Project"
  • Name it "LoginExample"
  • Create the JSP
    • In the "Web Content" folder, create a new JSP
    • Name it "LoginPage"
    • Place this code

    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <title>Login Page</title> </head> <body> <form action="LoginServlet"> Please enter your username <input type="text" name="un"/><br> Please enter your password <input type="text" name="pw"/> <input type="submit" value="submit"> </form> </body> </html>

As you can see; (in the LoginPage) when the user submits, the JSP calls "LoginServlet".This LoginServlet is intended to handle the Business logic associated with the request.

Create the LoginServlet by following these steps:

  • In the "src" folder, create a new "Package"
  • Name it "ExamplePackage"
  • In the "ExamplePackage", create a new "Servlet"
  • Name it "LoginServlet"
  • Place this code

    import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { try { UserBean user = new UserBean(); user.setUserName(request.getParameter("un")); user.setPassword(request.getParameter("pw")); user = UserDAO.login(user); if (user.isValid()) { HttpSession session = request.getSession(true); session.setAttribute("currentSessionUser",user); response.sendRedirect("userLogged.jsp"); //logged-in page } else response.sendRedirect("invalidLogin.jsp"); //error page } catch (Throwable theException) { System.out.println(theException); } } }

The login servlet instantiates a Bean that is of type "UserBean", and then calls the DAO named "UserDAO".

  • Our UserBean is a class representing the User table in our Database (where each column in the user table has a corresponding instance variable with a setter and a getter method).
  • The DAO, as said before, contains methods needed to communicate with the data source. In our example, the only needed method is the login method that checks if the username and password inputted by the user are valid or not.

Before implementing the DAO, you need to prepare your Data Source.

  1. Create a table in your DB
  2. Name it users
  3. Create the columns: 'FirstName', 'LastName', 'username', and 'password'
  4. Refer to your DB as a data source from "Administrative tools" in Control Panel

Please follow these steps to implement the Bean and the DAO

  • Create the "UserBean" class
    1. In the " ExamplePackage ", create a new "Class"
    2. Name it "UserBean"
    3. Place this code

      public class UserBean { private String username; private String password; private String firstName; private String lastName; public boolean valid; public String getFirstName() { return firstName; } public void setFirstName(String newFirstName) { firstName = newFirstName; } public String getLastName() { return lastName; } public void setLastName(String newLastName) { lastName = newLastName; } public String getPassword() { return password; } public void setPassword(String newPassword) { password = newPassword; } public String getUsername() { return username; } public void setUserName(String newUsername) { username = newUsername; } public boolean isValid() { return valid; } public void setValid(boolean newValid) { valid = newValid; } }

  • Create the "UserDAO" class
    1. In the " ExamplePackage ", create a new "Class"
    2. Name it "UserDAO"
    3. Place this code

      import java.text.*; import java.util.*; import java.sql.*; public class UserDAO { static Connection currentCon = null; static ResultSet rs = null; public static UserBean login(UserBean bean) { //preparing some objects for connection Statement stmt = null; String username = bean.getUsername(); String password = bean.getPassword(); String searchQuery = "select * from users where username='" + username + "' AND password='" + password + "'"; // "System.out.println" prints in the console; Normally used to trace the process System.out.println("Your user name is " + username); System.out.println("Your password is " + password); System.out.println("Query: "+searchQuery); try { //connect to DB currentCon = ConnectionManager.getConnection(); stmt=currentCon.createStatement(); rs = stmt.executeQuery(searchQuery); boolean more = rs.next(); // if user does not exist set the isValid variable to false if (!more) { System.out.println("Sorry, you are not a registered user! Please sign up first"); bean.setValid(false); } //if user exists set the isValid variable to true else if (more) { String firstName = rs.getString("FirstName"); String lastName = rs.getString("LastName"); System.out.println("Welcome " + firstName); bean.setFirstName(firstName); bean.setLastName(lastName); bean.setValid(true); } } catch (Exception ex) { System.out.println("Log In failed: An Exception has occurred! " + ex); } //some exception handling finally { if (rs != null) { try { rs.close(); } catch (Exception e) {} rs = null; } if (stmt != null) { try { stmt.close(); } catch (Exception e) {} stmt = null; } if (currentCon != null) { try { currentCon.close(); } catch (Exception e) { } currentCon = null; } } return bean; } }

The DAO uses a class named "ConnectionManager" to get a connection with the DB.

Create the "ConnectionManager" class:

  1. In the " ExamplePackage ", create a new "Class"
  2. Name it "ConnectionManager"
  3. Place this code

    import java.sql.*; import java.util.*; public class ConnectionManager { static Connection con; static String url; public static Connection getConnection() { try { String url = "jdbc:odbc:" + "DataSource"; // assuming "DataSource" is your DataSource name Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { con = DriverManager.getConnection(url,"username","password"); // assuming your SQL Server's username is "username" // and password is "password" } catch (SQLException ex) { ex.printStackTrace(); } } catch(ClassNotFoundException e) { System.out.println(e); } return con; } }

  4. In the pasted code, Replace
    • "DataSource" with your Data Source name
    • "username" with your SQL Server username
    • "password" with your SQL Server password

Finally, we are done with the logic and accessing the DB. So back to the interface, we need two JSPs; one for the valid login and another for the invalid. The two JSPs are

  • userLogged.jsp: Displays a message to welcome the user, using his first and last names (retrieved from the DB)
  • invalidLogin.jsp: Displays a message to inform the user that he is not a registered user

Steps to create the "userLogged" JSP

  1. In the "WebContent" folder, create a new "JSP"
  2. Name it "userLogged"
  3. Place this code

    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" import="ExamplePackage.UserBean" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <title> User Logged Successfully </title> </head> <body> <center> <% UserBean currentUser = (UserBean (session.getAttribute("currentSessionUser"));%> Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %> </center> </body> </html>

Steps to create the "invalidLogin" JSP

  1. In the "WebContent" folder, create a new "JSP"
  2. Name it "invalidLogin"
  3. Place this code

    <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <title>Invalid Login</title> </head> <body> <center> Sorry, you are not a registered user! Please sign up first </center> </body> </html>

Run the application , If you do not know any of the following steps, please check Steps 5-8 in the JSP Example

  • Set LoginPage.jsp to be your Home page (from web.xml)
  • Add your Project to Tomcat
  • Start Tomcat
  • Go to http://Localhost/loginExample
  • Test your project

This should be the result

Now your project should be working; if you would like to take a look at how the process went, go to the next page.

This diagram basically shows the process flow in our application

  1. The user enters his username and password in the fields displayed by the JSP - LoginPage.jsp -

  2. When the user submits, the servlet responsible for handling the request is called - LoginServlet -

  3. The Servlet is responsible for calling the appropriate method in the DAO so that it can indirectly interact with the DB.

    It is also responsible for setting and updating data saved in the bean, which will be used later by the DAO.

    In our application,
    • The LoginServlet creates a new instant of the UserBean and fills it with the username and the password entered by the user. The DAO will use this bean later to compare between the user input and the DB data
    • The Servlet calls the "login" method in the "UserDAO" to start performing its task

  4. The Login method, in the DAO, is responsible for checking whether the data entered by the user exists in the DB or not.

    In addition, it has to update the Bean's data that will be used later by the servlet.

    In our application,
    • The DAO uses the ConnectionManager class to get the DB connection
    • Query the DB (asks the DB to search for a user having certain username and password ) and checks,
      • If the ResultSet is empty, this means that the username and password were invalid (not in the DB).
      • If the ResultSet is not empty, this means that the username and password were valid.
    • Updates the UserBean.
      • In case of valid username and password, the DAO fills the bean with the rest of the user's information that will need to be displayed later by the JSP (first and last names).

        In addition, it sets the "valid" attribute of the bean to true.

      • Otherwise, the DAO sets the "valid" attribute of the bean to false

    Now we know if the user was registered or not

  5. Finally, the Servlet will check the validity of the user (by reading the valid attribute of the bean) and redirect to the appropriate JSP .
    • If valid, the servlet will
      • Add the bean as an attribute to the session. The bean will be used by the JSP to display the user's first and last names
      • Redirect to “userLogged.jsp” - That will welcome the user
    • If invalid, the servlet will redirect to “invalidLogin.jsp” - That will ask the user to sign up

RenewSession