Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Integrating JSP, Hibernate in an MVC application

jsp hibernate mvc html java

  • Please log in to reply
3 replies to this topic

#1 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 06 November 2012 - 10:57 AM

Introduction
While working on a Java based web application we come across a pattern of programming where we have a user based interface to interact with the application, a database as a source of application data and some business service and controller working in between them. Yes, you may have rightly guessed it is MVC pattern, where JSP pages acts a view layer, database as the model and some business service in the form of Java classes and Servlet as the controller. Here we shall use Hibernate framework as the ORM tool for data access. Though this is a oversimplified explanation, yet it will suit the purpose at least for getting started.

JSP
JSP is the acronym for Java Server Page. It is actually a HTML page with the added functionality of embedding Java code within HTML. JSP is responsible of interacting with the server or controller who in turn interacts with the database to request/response stream of data from the underlying repository.

Hibernate
Hibernate is a ORM framework which simplifies database interaction from Java code. With Hibernate you can write a complete database application without even writing a single SQL code. The reason for the existence of Hibernate is that - it is really very cumbersome working with database especially RDBMS from the view point of object oriented programming such as Java. You have to take care of opening database connection, closing connection, exceptions handling, transaction management manually with a whole lot of boilerplate code. Hibernate came in between and said to Java: I can make data access to RDBMS look object oriented and even you can interact with the database with your POJO (Plain Old Java Object) provided you give me a small XML or annotation based configuration file.

Software Requirements
For this project you may download and install the following
  • Java Software Development Kit: JDK
  • IDE: NetBeans (preferably, with all the feature including Tomcat Application Server)
  • Database: MySQL (install and configure it with user name and password, then create a database named test_db, consult help/manual if necessary)
  • JDBC Driver for MySQL: MySQL Connector/J (No installation required, simply unzip the file in any preferred location).
    Note: Hibernate and MySQL Connector/J comes with Netbeans, you may not need to download it at all.
Project Initiation
  • Open Netbeans
  • File, New Project, Select Java Web from the categories, then Web Application from the Projects list, Click Next
img1.jpg
  • Type a name of the project and leave the Project location and folder as default, then click Next
img2.jpg
  • Select Apache Tomcat Server if it not already selected and leave remaining options as default, then click Next
img3.jpg
  • Click on the check box Hibernate from the Frameworks list, then select New Database Connection... from Database Connection drop down list. Select MySQL (Connector/J driver) from the Driver drop down list and Add... the mysql-connector-java-**.jar from the location where you have unzipped MySQL Connector/J if it not already there in the Driver File(s) list. Click Next.
img4.jpg
  • Change the database name to test_db (which you have already created), user name to <your_username>, password to <your_password>. To test the connection click Text Connection. If it say Connection Succeeded, you are done, click Finish.
img5.jpg
  • Click Finish to complete the Project Wizard
img6.jpg

Hibernate Configuration
Once the project is setup the wizard will automatically include the the hibernate configuration file named hibernate.cfg.xml in appropriate location. Open the configuration file and add the following code with appropriate changes such as user name and password for the database.

<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull</property>
	 <property name="hibernate.connection.username">root</property>
	 <property name="hibernate.connection.password">admin</property>
	 <property name="show_sql">true</property>
	 <property name="hbm2ddl.auto">update</property>
	 <mapping class="org.app.model.User" />
</session-factory>
</hibernate-configuration>

Apart from the xml configuration file, there is a hibernate utility class. This class is the door to interact Java classes (POJO) with the Hibernate. Since SessionFactory is a very expensive object, in the sense that, it is a heavy weight class. It is in the best interest of the performance to have only one SessionFactory per application or database connection. So the class is declared as static and initialized within the static block. So whenever openSession method is called it returns the same SessionFactory's session object to different classes.

HibernateUtil.java
package org.app.util;

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

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
	 try {
		 sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
	 } catch (Throwable ex) {
		 System.err.println("Initial SessionFactory creation failed." + ex);
		 throw new ExceptionInInitializerError(ex);
	 }
}

public static Session openSession() {
	 return sessionFactory.openSession();
}
}
Model
Here our model class is User, a simple POJO ornamented with Java persistence annotation. This is our object oriented image in the form of Java class of the database table.

User.java


package org.app.model;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_TABLE")
public class User implements Serializable {

@Id @GeneratedValue
private Long id;
private String firstName;
private String middleName;
private String lastName;
private String email;
private String userId;
private String password;

//...Constructor and Getter Setter methods 	
}


Business Service
We have two business service classes viz. LoginService and RegisterService. Since only login and registration module is implemented, we have this two business service classes. Business service can be extended as per requirement.

LoginService.java
package org.app.service;
import java.util.ArrayList;
import java.util.List;
import org.app.model.User;
import org.app.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class LoginService {
public boolean authenticate(String userId, String password) {
	 User user = getUserByUserId(userId);		
	 if(user!=null && user.getUserId().equals(userId) && user.getPassword().equals(password)){
		 return true;
	 }else{
		 return false;
	 }
}
public User getUserByUserId(String userId) {
	 Session session = HibernateUtil.openSession();
	 Transaction tx = null;
	 User user = null;
	 try {
		 tx = session.getTransaction();
		 tx.begin();
		 Query query = session.createQuery("from User where userId='"+userId+"'");
		 user = (User)query.uniqueResult();
		 tx.commit();
	 } catch (Exception e) {
		 if (tx != null) {
			 tx.rollback();
		 }
		 e.printStackTrace();
	 } finally {
		 session.close();
	 }
	 return user;
}

public List<User> getListOfUsers(){
	 List<User> list = new ArrayList<User>();
	 Session session = HibernateUtil.openSession();
	 Transaction tx = null;	
	 try {
		 tx = session.getTransaction();
		 tx.begin();
		 list = session.createQuery("from User").list();					
		 tx.commit();
	 } catch (Exception e) {
		 if (tx != null) {
			 tx.rollback();
		 }
		 e.printStackTrace();
	 } finally {
		 session.close();
	 }
	 return list;
}
}

RegisterService.java
package org.app.service;
import org.app.model.User;
import org.app.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class RegisterService {
	
public boolean register(User user){
	 Session session = HibernateUtil.openSession();
	 if(isUserExists(user)) return false;	
	
	 Transaction tx = null;	
	 try {
		 tx = session.getTransaction();
		 tx.begin();
		 session.saveOrUpdate(user);		
		 tx.commit();
	 } catch (Exception e) {
		 if (tx != null) {
			 tx.rollback();
		 }
		 e.printStackTrace();
	 } finally {
		 session.close();
	 }	
	 return true;
}

public boolean isUserExists(User user){
	 Session session = HibernateUtil.openSession();
	 boolean result = false;
	 Transaction tx = null;
	 try{
		 tx = session.getTransaction();
		 tx.begin();
		 Query query = session.createQuery("from User where userId='"+user.getUserId()+"'");
		 User u = (User)query.uniqueResult();
		 tx.commit();
		 if(u!=null) result = true;
	 }catch(Exception ex){
		 if(tx!=null){
			 tx.rollback();
		 }
	 }finally{
		 session.close();
	 }
	 return result;
}
}

Controller
The two classes LoginServlet and RegisterServlet are two java servlets assist in interaction between view layer, business service classes which in turn interacts with the model layer.

LoginServlet.java
package org.app.controller;
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 org.app.model.User;
import org.app.service.LoginService;
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {	
	 String userId = request.getParameter("userId");	
	 String password = request.getParameter("password");
	 LoginService loginService = new LoginService();
	 boolean result = loginService.authenticate(userId, password);
	 User user = loginService.getUserByUserId(userId);
	 if(result == true){
		 request.getSession().setAttribute("user", user);		
		 response.sendRedirect("home.jsp");
	 }
	 else{
		 response.sendRedirect("login.jsp");
	 }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {
	 processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {
	 processRequest(request, response);
}
@Override
public String getServletInfo() {
	 return "Short description";
}
}

RegisterServlet.java
package org.app.controller;
import java.io.IOException;
import java.io.PrintWriter;
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 org.app.model.User;
import org.app.service.RegisterService;
@WebServlet(name = "RegisterServlet", urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {
	 response.setContentType("text/html;charset=UTF-8");
	 PrintWriter out = response.getWriter();
	 String fName = request.getParameter("firstName");
	 String mName = request.getParameter("middleName");
	 String lName = request.getParameter("lastName");
	 String email = request.getParameter("email");
	 String userId = request.getParameter("userId");
	 String password = request.getParameter("password");
	 User user = new User(fName,mName,lName, email,userId, password);
			
	 try {	
		 RegisterService registerService = new RegisterService();
		 boolean result = registerService.register(user);		
		 out.println("<html>");
		 out.println("<head>");		
		 out.println("<title>Registration Successful</title>");		
		 out.println("</head>");
		 out.println("<body>");
		 out.println("<center>");
		 if(result){
			 out.println("<h1>Registration Successful</h1>");
			 out.println("To login with new UserId and Password<a href=login.jsp>Click here</a>");
		 }else{
			 out.println("<h1>Registration Unsuccessful</h1>");
			 out.println("To try again<a href=register.jsp>Click here</a>");
		 }
		 out.println("</center>");
		 out.println("</body>");
		 out.println("</html>");
	 } finally {		
		 out.close();
	 }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {
	 processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		 throws ServletException, IOException {
	 processRequest(request, response);
}
@Override
public String getServletInfo() {
	 return "Short description";
}
}
View
There are several JSP files in the view layer. The coding within the files are simple HTML with some Java code embedded. The coding is self explanatory I believe :)

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">	
	 <link rel="stylesheet" type="text/css" href="style.css">
	 <title>Login Page</title>
</head>
<body>
<center>
	 <div id="mystyle" class="myform">
		 <form id="form" name="form" method="post" action="LoginServlet">
			 <h1>Login</h1>
			 <p>Please enter your login information
				 <br/>New User? <a href="register.jsp">Register</a></p>
			 <label>User ID
				 <span class="small">Enter your user ID</span>
			 </label>
			 <input type="text" name="userId" id="userId" />

			 <label>Password
				 <span class="small">Min. size 6 chars</span>
			 </label>
			 <input type="password" name="password" id="password" />

			 <button type="submit">Sign-in</button>
			 <div class="spacer"></div>
		 </form>
	 </div>
</center>
</body>
</html>


register.jsp

<%--
Document : register
Created on : Nov 5, 2012, 7:22:35 PM
Author	 : mano
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">	
	 <link rel="stylesheet" type="text/css" href="style.css">
	 <title>Registration Page</title>	
</head>
<body>
<center>
	 <div id="mystyle" class="myform">
		 <form id="form" name="form" method="post" action="RegisterServlet">
			 <h1>Registration</h1>
			 <p>Please enter the following information</p>

			 <label>First Name
				 <span class="small">Enter your first name</span>
			 </label>
			 <input type="text" name="firstName" id="firstName" />

			 <label>Middle Name
				 <span class="small">Enter your middle name</span>
			 </label>
			 <input type="text" name="middleName" id="middleName" />

			 <label>Last Name
				 <span class="small">Enter your last name</span>
			 </label>
			 <input type="text" name="lastName" id="lastName" />

			 <label>Email
				 <span class="small">Ex: eric20@gmail.com</span>
			 </label>
			 <input type="text" name="email" id="email" />

			 <label>User ID
				 <span class="small">Enter your user ID</span>
			 </label>
			 <input type="text" name="userId" id="userId" />

			 <label>Password
				 <span class="small">Password min. 6 chars</span>
			 </label>
			 <input type="text" name="password" id="password" />

			 <button type="submit">Register</button>
			 <div class="spacer"></div>

		 </form>
	 </div>
</center>
</body>
</html>


logout.jsp

<%--
Document : logout
Created on : Nov 5, 2012, 7:53:21 PM
Author	 : mano
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">	
	 <link rel="stylesheet" type="text/css" href="style.css">
	 <title>logout Page</title>
</head>
<body>
	 <%		
		 session.removeAttribute("userId");
		 session.removeAttribute("password");
		 session.invalidate();
	 %>
<center>
	 <h1>You have successfully logged out</h1>
	 To login again <a href="login.jsp">click here</a>.
</center>
</body>
</html>


home.jsp

<%--
Document : index
Created on : Nov 5, 2012, 6:06:23 PM
Author	 : mano
--%>

<%@page import="java.util.List"%>
<%@page import="org.app.service.LoginService"%>
<%@page import="java.util.Date"%>
<%@page import="org.app.model.User"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	 <link rel="stylesheet" type="text/css" href="style.css"/>
	 <title>Home Page</title>	
</head>
<body>
<center>
	 <div id="mystyle">
		 <h1>Java, C++, J2EE, Tutorial</h1>
		 <p><a href="http://www.forum.codecall.net">http://www.forum.codecall.net</a><br/>
			 <b>Integrating JSP, Hibernate in an MVC Application</b><br/>
			 <%=new Date()%></br>
			 <%
				 User user = (User) session.getAttribute("user");
			 %>		
			 <b>Welcome <%= user.getFirstName() + " " + user.getLastName()%></b>		
			 <br/>
			 <a href="logout.jsp">Logout</a>
		 </p>

		 <table>
			 <thead>
				 <tr>
					 <th>User ID</th>
					 <th>First Name</th>
					 <th>Middle Name</th>
					 <th>Last Name</th>
					 <th>email</th>					
				 </tr>
			 </thead>
			 <tbody>
				 <%
					 LoginService loginService = new LoginService();
					 List<User> list = loginService.getListOfUsers();
					 for (User u : list) {
				 %>
				 <tr>
					 <td><%=u.getUserId()%></td>
					 <td><%=u.getFirstName()%></td>
					 <td><%=u.getMiddleName()%></td>
					 <td><%=u.getLastName()%></td>
					 <td><%=u.getEmail()%></td>
				 </tr>
				 <%}%>
			 <tbody>
		 </table>		
		 <br/>
	 </div>

</center>		
</body>
</html>


Look and Feel
A CSS stylesheet is linked to the JSP file for the look and feel of the pages in the browser. It has nothing to do with the functionality of the application

style.css

/*
Document : style
Created on : Nov 5, 2012, 7:03:03 PM
Author	 : mano
Description:
Purpose of the stylesheet follows.
*/
root {
display: block;
}
body{
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}
p, h1, form, button{border:0; margin:0; padding:0;}
.spacer{clear:both; height:1px;}
.myform{
margin:0 auto;
width:400px;
padding:14px;
}

#mystyle{
border:solid 2px burlywood;
background: antiquewhite;
border-radius: 5px;
}
#mystyle h1 {
font-size:14px;
font-weight:bold;
margin-bottom:8px;
}
#mystyle p{
font-size:11px;
color:#666666;
margin-bottom:20px;
border-bottom:solid 1px burlywood;
padding-bottom:10px;
}
#mystyle label{
display:block;
font-weight:bold;
text-align:right;
width:140px;
float:left;
}
#mystyle .small{
color:#666666;
display:block;
font-size:11px;
font-weight:normal;
text-align:right;
width:140px;
}
#mystyle input{
float:left;
font-size:12px;
padding:4px 2px;
border:solid 1px burlywood;
width:200px;
margin:2px 0 20px 10px;
border-radius: 5px;
}
#mystyle button{
clear:both;
margin-left:150px;
width:125px;
height:31px;
background:#666666;
text-align:center;
line-height:31px;
color:#FFFFFF;
font-size:11px;
font-weight:bold;
border-radius: 5px;
}
table, tr, td{
border-radius: 5px;
border:solid 1px burlywood;
padding: 5px;
width: max-content;
}
For convenience you may check the structure and arrangement of the files in the project.
img7.jpg

Output Screenshots

Login Page
img8.jpg

Registration Page
img9.jpg

Home page
img10.jpg



Attached Source code
Attached File  src.zip   9.13KB   4688 downloads

  • 1

#2 OscarNahum

OscarNahum

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 13 May 2013 - 05:27 PM

Thanks a lot! It was really really useful for me :D


  • 0

#3 MathX

MathX

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1038 posts
  • Programming Language:Java

Posted 12 October 2013 - 11:13 AM

Nicely done!


  • 0

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!


#4 PrathapKumar

PrathapKumar

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 14 January 2016 - 09:15 PM

it  is really great article on Integration o JSP and Hibernate. DO you have any article on JSF with Hibernate

 

Java Training in Chennai


  • 0





Also tagged with one or more of these keywords: jsp, hibernate, mvc, html, java