Login Example using Servlet, JSP, Oracle DB and Hibernate Framework.

This example shows how to create a simple login application using Servlet, jsp, Oracle DB and Hibernate framework. In this application developer no need to create Table structure in Oracle Database, Hibernate framework will take care creation of the table structure. Developer needs to create a Schema or User account in Oracle DB and configure DB username and password details in application file hibernate.cfg.xml. In this application configured Oracle DB schema or user is a Gurugubelli and password also a Gurugubelli. And user need to add below .jar files in application lib folder as per Java web application standards.
Below Jar files are available with Hibernate framework. (for more clarification see the previous post: Click Here)
  • antlr-2.7.7.jar
  • cdi-api-1.1.jar
  • classmate-1.3.0.jar
  • dom4j-1.6.1.jar
  • el-api-2.2.jar
  • geronimo-jta_1.1_spec-1.1.1.jar
  • hibernate-commons-annotations-5.0.1.Final.jar
  • hibernate-core-5.2.4.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • jandex-2.0.0.Final.jar
  • javassist-3.20.0-GA.jar
  • javax.inject-1.jar
  • jboss-interceptors-api_1.1_spec-1.0.0.Beta1.jar
  • jboss-logging-3.3.0.Final.jar
  • jsr250-api-1.0.jar
Below 2 .jar files are available with Tomcat Server (under %Tomcat_Home%/lib folder)
  • servlet-api.jar
  • jsp-api.jar
Below ojdbc14.jar file is available with Oracle instillation (under  %Oracle_Home%\app\oracle\product\10.2.0\server\jdbc\lib folder)
  • ojdbc14.jar
Note: Oracle ojdbcXX.jar file version is different from Oracle version to version.
For developing application using eclipse IDE software, create a Dynamic web project and create the project structure like below screen short.


User.java is the DTO object, means this is the Data Transfer Object between the application layers. from Controller layer to Service layer, Service layer to DAO Layer etc....
package com.gurugubelli.pojo;

public class User {
 private String username;
 private String password;
 private String firstName;
 private String lastName;
 private String dob;
 private String mobileNo;
 private String emailId;

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDob() {
  return dob;
 }

 public void setDob(String dob) {
  this.dob = dob;
 }

 public String getMobileNo() {
  return mobileNo;
 }

 public void setMobileNo(String mobileNo) {
  this.mobileNo = mobileNo;
 }

 public String getEmailId() {
  return emailId;
 }

 public void setEmailId(String emailId) {
  this.emailId = emailId;
 }

 @Override
 public String toString() {
  return "User [username=" + username + ", password=" + password
    + ", firstName=" + firstName + ", lastName=" + lastName
    + ", dob=" + dob + ", mobileNo=" + mobileNo + ", emailId="
    + emailId + "]";
 }
}
Below .xml file is the configuration file between the Hibernate framework and Oracle DB, based on the below configuration hibernate create a Table in Oracle DB.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.gurugubelli.pojo.User" table="user_data">
  <id name="username">
   <column name="username" length="20" />
  </id>
  <property name="password" column="password" length="20" />
  <property name="firstName" column="first_name" length="20" />
  <property name="lastName" column="last_name" length="20" />
  <property name="dob" column="dob" />
  <property name="mobileNo" column="mobile_no" length="10" />
  <property name="emailId" column="email_id" length="25" />
 </class>
</hibernate-mapping>


hibernate.cfg.xml :
It is an .xml file, in which DB connection details like username, password, url and Driver Class name etc... & hibernate properties like Dialect, show_sql and hbm2ddl.auto etc....
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
  <property name="connection.username">gurugubelli</property>
  <property name="connection.password">gurugubelli</property>
  <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property>
  <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
  <property name="show_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
  <mapping resource="com/gurugubelli/config/User.hbm.xml" />
 </session-factory>
</hibernate-configuration> 

You know very well every Java web application must have deployment descriptor configuration for application (either .xml or annotation configuration), below is the web.xml file for our application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <servlet>
  <servlet-name>LoginController</servlet-name>
  <servlet-class>com.gurugubelli.controller.LoginController</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>LoginController</servlet-name>
  <url-pattern>/login</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>UserRegistration</servlet-name>
  <servlet-class>com.gurugubelli.controller.RegistrationController</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>UserRegistration</servlet-name>
  <url-pattern>/registration</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>login.jsp</welcome-file>
 </welcome-file-list>
</web-app>

In above web.xml file configured welcome file as a login.jsp page and Servlet class with urls login, registration. here Servlet class are controllers for this application. see the below two controllers.
package com.gurugubelli.controller;

import java.io.IOException;

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

import com.gurugubelli.service.BaseService;
import com.gurugubelli.service.BaseServiceImpl;

/**
 * Servlet implementation class LoginController
 */
public class LoginController extends HttpServlet {
 private static final long serialVersionUID = 1L;


 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.sendRedirect("login.jsp");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  
  System.out.println(username + " :: " + password);
  String page = "login.jsp";
  if(username.trim().length() >= 0 && username != null &&
    password.trim().length() >= 0 && password != null) {
   BaseService loginService = new BaseServiceImpl();
   boolean flag = loginService.login(username, password);
   if(flag) {
    System.out.println("Login success!!!");
    request.setAttribute("username", username);
    request.setAttribute("msg", "Login Success.....");
    page = "home.jsp";
   } else {
    request.setAttribute("msg", "Wrong Username or Password, Try again!!!");
   }
  } else {
   request.setAttribute("msg", "Please enter username and password...");
  }
  request.getRequestDispatcher(page).include(request, response);
 }
}

package com.gurugubelli.controller;

import java.io.IOException;

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

import com.gurugubelli.dao.BaseDao;
import com.gurugubelli.dao.BaseDaoImpl;
import com.gurugubelli.pojo.User;


public class RegistrationController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.sendRedirect("userRegistration.jsp");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String msg = "Password and Conform Passwords must be same";
  String page = "userRegistration.jsp";
  if(request.getParameter("password").equals(request.getParameter("confPassword"))){
   User user = new User();
   user.setUsername(request.getParameter("username"));
   user.setPassword(request.getParameter("password"));
   user.setFirstName(request.getParameter("firstName"));
   user.setLastName(request.getParameter("lastName"));
   user.setDob(request.getParameter("dob"));
   user.setEmailId(request.getParameter("emailId"));
   user.setMobileNo(request.getParameter("mobileNo"));
   
   System.out.println(user.toString());
   BaseDao baseDao = new BaseDaoImpl();
   msg = baseDao.register(user);
   page = "login.jsp";
  } 
  request.setAttribute("msg2", msg);
  request.getRequestDispatcher(page).include(request, response);
 }

}

Below are the Service declaration and Implementation Classes
package com.gurugubelli.service;

import com.gurugubelli.pojo.User;

public interface BaseService {
 public boolean login(String username, String password);

 public String registration(User user);
}

package com.gurugubelli.service;

import com.gurugubelli.dao.BaseDao;
import com.gurugubelli.dao.BaseDaoImpl;
import com.gurugubelli.pojo.User;

public class BaseServiceImpl implements BaseService {

 private BaseDao loginDao = new BaseDaoImpl();

 @Override
 public boolean login(String username, String password) {
  return loginDao.login(username, password);
 }

 @Override
 public String registration(User user) {
  return loginDao.register(user);
 }

}

Below are the Dao Declaration and Implementation Classes
package com.gurugubelli.dao;

import com.gurugubelli.pojo.User;

public interface BaseDao {
 public boolean login(String username, String password);

 public String register(User user);
}


package com.gurugubelli.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.gurugubelli.pojo.User;
import com.gurugubelli.util.HibernateUtil;

public class BaseDaoImpl implements BaseDao {

 @Override
 public boolean login(String username, String password) {
  Session session = HibernateUtil.getSession();
  if (session != null) {
   try {
    User user = (User) session.get(User.class, username);
    if (password.equals(user.getPassword())) {
     System.out.println("User: " + user.toString());
     return true;
    }
   } catch (Exception exception) {
    System.out.println("Exception occred while reading user data: "
      + exception.getMessage());
    return false;
   }

  } else {
   System.out.println("DB server down.....");
  }
  return false;
 }

 @Override
 public String register(User user) {
  String msg = "Registration unsuccessful, try again.....";
  Session session = HibernateUtil.getSession();
  if (session != null) {
   try {
    if (user != null) {
     String username = (String) session.save(user);
     session.beginTransaction().commit();
     msg = "User " + username
       + " created successfully, please login...";
    }
   } catch (Exception exception) {
    System.out.println("Exception occred while reading user data: "
      + exception.getMessage());
   }

  } else {
   System.out.println("DB server down.....");
  }
  System.out.println("msg:" + msg);
  return msg;
 }
}

Hibernate Utility Class for Application. Using this class creating Hibernate connection and using this connection in Application Dao Implementation class
package com.gurugubelli.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static Configuration configuration;
 private static SessionFactory sessionFactory;

 static {
  configuration = new Configuration()
    .configure("com/gurugubelli/config/hibernate.cfg.xml");
  sessionFactory = configuration.buildSessionFactory();
 }

 public static Session getSession() {
  Session session = null;
  if (sessionFactory != null) {
   session = sessionFactory.openSession();
  }
  return session;
 }
}


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>:: Login ::</title>
</head>
<body>
 </br> </br> </br>
 <h1>
  <div align="center">
   <% if(request.getAttribute("msg") != null) { %>
    <p style="color: red">
     <%= request.getAttribute("msg") %>
    </p>
   <% } %>
   <% if(request.getAttribute("msg2") != null) { %>
    <p style="color: green;">
     <%= request.getAttribute("msg2") %>
    </p>
   <% } %>

   <form action="login" method="POST">
    <label>Enter Username : </label> 
    <input type="text" name="username" required="required"> <br> <br> 
    <label>Enter Password : </label> 
    <input type="password" name="password" required="required"> <br> <br> 
    <input type="submit" value="Login">
   </form>
 </h1>
 </div>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>User Registration</title>
</head>
<body>
 </br></br></br></br>
 <h2 align="center">
 <% if(request.getAttribute("msg2") != null) { %>
  <p style="color: red">
   <%= request.getAttribute("msg2") %>
  </p>
 <% } %>
 </h2>
 <div align="center">
  <form action="userRegistration" method="post">
   <table align="center" border="1">
    <tr>
     <td colspan="2" align="center"><b>User Registration</b></td>
    </tr>
    <tr>
     <td>Username* :</td>
     <td><input type="text" name="username" required></td>
    </tr>
    <tr>
     <td>Password* :</td>
     <td><input type="password" name="password" required></td>
    </tr>
    <tr>
     <td>Conform Password* :</td>
     <td><input type="password" name="confPassword" required></td>
    </tr>
    <tr>
     <td>First Name* :</td>
     <td><input type="text" name="firstName" required></td>
    </tr>
    <tr>
     <td>Last Name* :</td>
     <td><input type="text" name="lastName" required></td>
    </tr>
    <tr>
     <td>Date of Birth* :</td>
     <td><input type="date" name="dob" required></td>
    </tr>
    <tr>
     <td>Mobile Number :</td>
     <td><input type="number" name="mobileNo"></td>
    </tr>
    <tr>
     <td>Email Id :</td>
     <td><input type="email" name="emailId"></td>
    </tr>
    <tr>
     <td align="center"><input type="submit" value="Register User"></td>
     <td align="center"><input type="reset" name="Reset Form"></td>
    </tr>
   </table>
  </form>
 </div>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>:: Home ::</title>
</head>
<body>
<table width="100%">
 <tr bgcolor=F9F9F3>
  <td align="left"><h1>Login Success.....</h1></td>
  <td align="right"> 
  <h2>
   Hi, <%= request.getAttribute("username") %>
  </h2>
  </td>
 </tr>
 <tr>
  <td colspan="2"><h1 align="center"></br></br>comming soon...., website under construction</h1></td>
 </tr>
</table>
</body>
</html>

Find the below Test Cases and Application Flow:





















Login Example using Servlet, JSP, Oracle DB and Hibernate Framework. Login Example using Servlet, JSP, Oracle DB and Hibernate Framework. Reviewed by Gurugubelli Technologies on January 29, 2017 Rating: 5

1 comment:

  1. Learned a lot of new things from your post!Good creation ,thanks for good info Oracle SOA Online Training Bangalore

    ReplyDelete

Powered by Blogger.