Thursday, August 28, 2014

Login application using jsp servlet and mysql database

Today we are going to create a simple web login application using JSP, servlet and mysql database. In order to create an application we are going to use the following software.

  1. MySql database
  2. Eclipse IDE
  3. Tomcat server
Firstly, lets create a database and a table in mysql. Turn on the database connection and open the mysql command prompt and paste the below code.

  1. create database form;  
  2.   
  3. use form;  
  4.   
  5. CREATE  TABLE `form`.`login` (  
  6.   `user` VARCHAR(20) NOT NULL ,  
  7.   `password` VARCHAR(20) NOT NULL ,  
  8.   PRIMARY KEY (`user`) );   
  9. INSERT INTO `form`.`login` (`user`, `password`) VALUES ('Admin''passw0rd');  

Now, open up the Eclipse IDE and create a dynamic web project and create the project structure as per the screen shot below.



Lets create the front end with two basic jsp pages.

index.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  6. <title>Login Application</title>  
  7. </head>  
  8. <body>  
  9.     <form action="loginServlet" method="post">  
  10.         <fieldset style="width: 300px">  
  11.             <legend> Login to App </legend>  
  12.             <table>  
  13.                 <tr>  
  14.                     <td>User ID</td>  
  15.                     <td><input type="text" name="username" required="required" /></td>  
  16.                 </tr>  
  17.                 <tr>  
  18.                     <td>Password</td>  
  19.                     <td><input type="password" name="userpass" required="required" /></td>  
  20.                 </tr>  
  21.                 <tr>  
  22.                     <td><input type="submit" value="Login" /></td>  
  23.                 </tr>  
  24.             </table>  
  25.         </fieldset>  
  26.     </form>  
  27. </body>  
  28. </html>  


welcome.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  6. <title>Welcome <%=session.getAttribute("name")%></title>  
  7. </head>  
  8. <body>  
  9.     <h3>Login successful!!!</h3>  
  10.     <h4>  
  11.         Hello,  
  12.         <%=session.getAttribute("name")%></h4>  
  13. </body>  
  14. </html>  


Now, lets create the login DAO which will enable us to connect our login application with mysql database and execute the query to the DB.

LoginDao.java
  1. package com.amzi.dao;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8.   
  9. public class LoginDao {  
  10.     public static boolean validate(String name, String pass) {          
  11.         boolean status = false;  
  12.         Connection conn = null;  
  13.         PreparedStatement pst = null;  
  14.         ResultSet rs = null;  
  15.   
  16.         String url = "jdbc:mysql://localhost:3306/";  
  17.         String dbName = "form";  
  18.         String driver = "com.mysql.jdbc.Driver";  
  19.         String userName = "root";  
  20.         String password = "password";  
  21.         try {  
  22.             Class.forName(driver).newInstance();  
  23.             conn = DriverManager  
  24.                     .getConnection(url + dbName, userName, password);  
  25.   
  26.             pst = conn  
  27.                     .prepareStatement("select * from login where user=? and password=?");  
  28.             pst.setString(1, name);  
  29.             pst.setString(2, pass);  
  30.   
  31.             rs = pst.executeQuery();  
  32.             status = rs.next();  
  33.   
  34.         } catch (Exception e) {  
  35.             System.out.println(e);  
  36.         } finally {  
  37.             if (conn != null) {  
  38.                 try {  
  39.                     conn.close();  
  40.                 } catch (SQLException e) {  
  41.                     e.printStackTrace();  
  42.                 }  
  43.             }  
  44.             if (pst != null) {  
  45.                 try {  
  46.                     pst.close();  
  47.                 } catch (SQLException e) {  
  48.                     e.printStackTrace();  
  49.                 }  
  50.             }  
  51.             if (rs != null) {  
  52.                 try {  
  53.                     rs.close();  
  54.                 } catch (SQLException e) {  
  55.                     e.printStackTrace();  
  56.                 }  
  57.             }  
  58.         }  
  59.         return status;  
  60.     }  
  61. }  


Now, we are going to create the servlet which will capture the input parameter from the jsp and validate it against the LoginDao.

LoginServlet.java
  1. package com.amzi.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.RequestDispatcher;  
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import javax.servlet.http.HttpSession;  
  12.   
  13. import com.amzi.dao.LoginDao;  
  14.   
  15. public class LoginServlet extends HttpServlet{  
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.   
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)    
  20.             throws ServletException, IOException {    
  21.   
  22.         response.setContentType("text/html");    
  23.         PrintWriter out = response.getWriter();    
  24.           
  25.         String n=request.getParameter("username");    
  26.         String p=request.getParameter("userpass");   
  27.           
  28.         HttpSession session = request.getSession(false);  
  29.         if(session!=null)  
  30.         session.setAttribute("name", n);  
  31.   
  32.         if(LoginDao.validate(n, p)){    
  33.             RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");    
  34.             rd.forward(request,response);    
  35.         }    
  36.         else{    
  37.             out.print("<p style=\"color:red\">Sorry username or password error</p>");    
  38.             RequestDispatcher rd=request.getRequestDispatcher("index.jsp");    
  39.             rd.include(request,response);    
  40.         }    
  41.   
  42.         out.close();    
  43.     }    
  44. }   


Finally, lets configure the web.xml file for servlet and welcome file configuration.

web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app  
  3.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"  
  5.     version="2.5">  
  6.     <servlet>  
  7.         <servlet-name>login</servlet-name>  
  8.         <servlet-class>com.amzi.servlets.LoginServlet</servlet-class>  
  9.     </servlet>  
  10.   
  11.     <servlet-mapping>  
  12.         <servlet-name>login</servlet-name>  
  13.         <url-pattern>/loginServlet</url-pattern>  
  14.     </servlet-mapping>  
  15.   
  16.     <welcome-file-list>  
  17.         <welcome-file>index.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19. </web-app>  


That's all it takes to create a simple web login application. This is not the ideal login application as it needs lot of modification such as security etc. Anyways, for now let's run the project on the tomcat server and test the application.



Now, let's input the invalid data and check the result.



Now, I am using the correct credentials which will match with the database result and redirect the page to the welcome file.

Note: The URL is internally redirecting the page to the welcome.jsp file since we are using the forward method. If instead we would have used redirect method, in that case we can see the request URL in the browser. 


Download Code



ref: http://javaandj2eetutor.blogspot.com/2014/01/login-application-using-jsp-servlet-and.html