Wednesday, September 18, 2013

Creating a Simple Login Form using JSPs and Servlets in Eclipse - Part 2

Hi Guys,

In 'Part 1', we saw how to create a simple login jsp(LoginForm.jsp) page. Now, let this jsp page works for us.

Note: If you didn't go through the 'Part 1', you can go through it here.

    If  we enter the UserId and Password values in the 'LoginForm.jsp' which we created in Part 1 and when clicked on 'submit' then we get the following error page.





It says, 'The requested resource is not available' and the requested resource is '/Login/LoginServlet'.

In 'LoginForm.jsp' while creating login form, we mentioned that the action servlet as 'LoginServlet' using the below statement

<form action=LoginServlet>

But, we haven't created this servlet. When we run the 'LoginForm.jsp' and entered the 'UserId', 'Password' values and submitted them then the 'LoginForm' page tries to submit the form to 'LoginServlet' page, but it is unable to find the 'LoginServlet' page and hence the error page is getting displayed. So, to avoid this 404 error page, we need to create 'LoginServlet' page, this is where the form attributes are processed. Now let us create a LoginServlet java class to handle the business logic associated with the request.

Step 1: Creating LoginServlet
    First we will create a Package. To create a package go to 'Project  Explorer' in eclipse and expand 'Java Resources' in 'Login' project and right click on 'src' folder, and select 'New' --> 'Package'.


After that, need to create servlet. To create a servlet, right click on 'ganeshtechblog' package under src, and then select 'New' --> 'Servlet'.


and give 'LoginServlet' as 'Class name:' and click 'Finish'.


Then, 'LoginServlet.java' will be created with the default implementation.Now we need to have our own implementation which includes,

1. getting the submitted form data from 'LoginForm.jsp'
2. processing the data
3. sending the response back to the user.

Lets see now, how to implement all these steps.

Step 1.1: getting the submitted form data from 'LoginForm.jsp' 

    Whenever  a client sends a request to the server then the server(a.k.a servlet container, ex: Apache Tomcat) creates an HttpServletRequest object and an HttpServletResponse object and passes them as arguments to the servlet's service methods such as doGet, doPost, etc. and HttpServletRequest provides the functionality to the classes to access all the form data received in the HTTP request. So, we can get the form elements with the help of HttpServletRequest.getParameter(String parameterName). Nothing to do much here except reading input parameters.

Step 1.2: processing the data

     Once we got the input data (UserId and Password) from HttpServletRequest.getParameter() then we need to query the database for the entries (userId and Password). If the entries exists in the database then we can redirect the page to a welcome page otherwise to an error page saying invalid input (means user not registered earlier). So, we need to have a database with some data against we will test our login application with some input data. 

    We use JDBC APIs to connect to the database, process and retrieve the results from the database. For this article, we use MySQL database to store the user data (UserId, Password, FirstName and LastName), because its simple and open source and therefore we use the connection string for MySQL as "jdbc:mysql://localhost:8888/myDb" and database name as "myDb" with the userName as "myUser" and password as "myPassword". 

Step  1.3: sending the response back to the user.

After connecting to the database, we query the database for the given 'UserId' and 'Password'. If entries found in the database then we ask the servlet to redirect to a success page (LoginSuccess.jsp) otherwise to an error page (LoginFailure.jsp).

Copy the below code into LoginServlet.java.


package ganeshtechblog;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

import javax.servlet.http.HttpSession;
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        String password = request.getParameter("pwd");
        String searchQuery = "select * from users where username='" + userId
                + "' AND password='" + password + "'";
        try {
   Class.forName("com.mysql.jdbc.Driver");
  } 
        catch (ClassNotFoundException e) {
   System.out.println(e.getMessage());
  }
        try {
         Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/myDb", "root", "");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(searchQuery);
            boolean isEmpty = rs.next();
            if (!isEmpty) {
                // redirect to error page
                response.sendRedirect("LoginFailure.jsp");
            }
            else if (isEmpty) {
                // fetch the session from request, create new session if session
                // is not present in the request
                HttpSession session = request.getSession(true);
                session.setAttribute("FirstName", rs.getString("firstname"));
                session.setAttribute("LastName", rs.getString("lastname"));
                // redirect to success page
                response.sendRedirect("LoginSuccess.jsp");
            }
        }
        catch (SQLException e) {
            System.out.println("SQLException occured: " + e.getMessage());
            e.printStackTrace();
        }
    }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}


Now we need to get the JDBC driver for MySQL to let our servlet code works. You can get it from here. Download the zip archive (ex: mysql-connector-java-5.1.26.zip) by selecting the platform "Platform Independent" from the select menu. Unzip the archive and copy the jar file (ex: mysql-connector-java-5.1.26-bin.jar) into the lib folder of apache tomcat installation directory(ex: D:\GAP\GaneshTechBlog\apache-tomcat-7.0.42\lib). Restart the tomcat server from "Servers" perspective by right clicking on the "Tomcat Server" instance and by selecting "Restart" option from the menu as shown below:



Note: Don't run the application now. If you do so, you will get 'ConnectException' as database is not set yet.

3 comments:

  1. hello
    iam new to java programming...
    so i was able to follow your guide upto creating a servlet...
    but after that what to do

    ReplyDelete
  2. Hi,

    In the picture on the top of page 2, you show the 404 error.

    But what you also do is sending the password in cleartext in the url. How can you avoid this, and still retrieve the password on the servlet side?

    ReplyDelete
  3. Simply put the form method as POST instead of GET!
    it masks your sensitive information!

    ReplyDelete