Thursday, 15 March 2012

jsp login page creation in eclipse


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
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

No comments:

Post a Comment