Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for connectivity from Hibernate through Servlet application
Previous Home Next

In this Servlet application, make Servlet application connectivity through Hibernate framework.Consider following steps for creating this application

Step-1 Create a new web project and name it as Hibernate&Servlet . Now adding Hibernate capability into application from framework options window. Provide database connection URL along with database dialect, which later configure itself into hibernate.cfg.xml file.

Step-2 Right click over default package and go to New -> other ->New File , window open (as show into below picture). Now choose Hibernate from the Categories list and and Hibernate Mapping Wizard from File Types list, then click on Next button.

Step-3 Now New Hibernate Mapping Wizard window open, Specify the values as shown in below picture. After fill all the entry click on Next button.

Step-4 Now configure class, configure xml file and database table into hibernate.hbm.xml file.

Application directory structure

Hibernate.cfg.xml

<?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/r4r</property>
    <property name="hibernate.connection.username">
	  root</property>
    <property name="hibernate.connection.password">
	  root</property>
    <mapping resource="hibernate.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.hbm.xml

<?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="r4r.Hibernate.Servlet.HibernateBean" table="pet">
  <id name="id" type="int" >
<generator class="increment" /> 
  </id>
  <property name="name" />
  <property name="ownername" />
  <property name="species" />
  <property name="gender" />
  <property name="birth" />
  <property name="death" />

 </class>
</hibernate-mapping>

HibernateBean Class

/*
 * Save as a HibernateBean.java
 */
package r4r.Hibernate.Servlet;

/**
 *
 * @author R4R
 */
public class HibernateBean {

 private int id;
 private String name;
 private String ownername;
 private String species;
 private String gender;
 private String birth;
 private String death;
 
 //---------------- constructor
 public HibernateBean() {
 }

 public HibernateBean(String name, String ownername,
	 String species, String gender, String birth, String death)
{
  this.name = name;
  this.ownername = ownername;
  this.species = species;
  this.gender = gender;
  this.birth = birth;
  this.death = death;
 }
 
 //------------ Getter/Setter
 public String getBirth() {
  return birth;
 }

 public void setBirth(String birth) {
  this.birth = birth;
 }

 public String getDeath() {
  return death;
 }

 public void setDeath(String death) {
  this.death = death;
 }

 public String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getOwnername() {
  return ownername;
 }

 public void setOwnername(String ownername) {
  this.ownername = ownername;
 }

 public String getSpecies() {
  return species;
 }

 public void setSpecies(String species) {
  this.species = species;
 }
}

HibernateDAO class

/*
 * Save as a HibernateDAOClass.java
 */
package r4r.Hibernate.Servlet;

import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author R4R
 */
public class HibernateDAOClass {

 public List<HibernateBean> getFetchData() {
  //get inforamtion in hibernate.cfg.xml file
  Configuration cfg = new Configuration().configure(); 
 /*create session instance
 (and load database property in hibernate.cfg.xml file)
  */
  SessionFactory f = cfg.buildSessionFactory();
  //Open session
  Session session = f.openSession();
  //data access form hibernate.cfg.xml file
  Transaction t = session.beginTransaction();

  try {
//Create quary
Query q = session.createQuery("from HibernateBean");
return (q.list());
  } finally {
t.commit(); //free resource
session.clear();
session.close();
  }
 }

 public void getInsertData(String name, String ownername,
	    String species, String gender, String birth, String death)
{
  Configuration cfg = new Configuration().configure();
  SessionFactory f = cfg.buildSessionFactory();
  Session session = f.openSession();
  Transaction t = session.beginTransaction();
  HibernateBean hbBean = 
	 new HibernateBean(name, ownername, species, gender, birth, death);
  session.save(hbBean); // save data into database
  t.commit();  //free resource
  session.clear();
  session.close();
 }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
  xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <servlet>
  <servlet-name>HibernateServlet</servlet-name>
  <servlet-class>r4r.Hibernate.Servlet.HibernateServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>HibernateServlet</servlet-name>
  <url-pattern>/HibernateServlet</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>
      30
  </session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-index</title>
 </head>
 <body>
    <h1>Hibernate and Servlet Connectivity Application!</h1>
    <form action="HibernateServlet" method="POST">
      Enter PetName: <input type="text" name="name" 
	           value="" size="30" maxlength="10" /><br/>
      Enter OwnerName: <input type="text" name="ownername"
	           value="" size="30" maxlength="10" /><br/>
      Enter Species: <input type="text" name="species"
	           value="" size="30" maxlength="10"/><br/>
      Enter Gender: <input type="radio" name="gender"
	              value="m" />Male
       <input type="radio" name="gender"
	            value="m" />Female <br/>
      Birth Date: <input type="text" name="birth"
	    value="" size="30" maxlength="10" />(0000-00-00)<br/>
      Death Data: <input type="text" name="death" 
	    value="" size="30" maxlength="10" />(0000-00-00)<br/>
      <input type="submit" value="Insert Data" name="insert" />
      <input type="submit" value="Fetch Data" name="fetch" />
    </form>
 </body>
</html>

Servlet Program

/*
 * Save as a HibernateServlet.java
 */
package r4r.Hibernate.Servlet;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
/**
 *
 * @author R4R
 */
public class HibernateServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException
 {
 }
 @Override
 protected void doPost(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException 
{
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  // get value form TextField form index.jsp page
  String name = request.getParameter("name");
  String ownername = request.getParameter("ownername");
  String species = request.getParameter("species");
  String gender = request.getParameter("gender");
  String birth = request.getParameter("birth");
  String death = request.getParameter("death");

  //user won't allow to leave any field blank
  if (request.getParameter("insert") != null) {
//Insert data into database
if (!name.equals("") || !ownername.equals("") || !species.equals("")
  || !birth.equals("") || !death.equals("")) {
 //invoke HibernateDAOClass object
 HibernateDAOClass dao = new HibernateDAOClass();
 //passing data to HibernateDAOClass
 dao.getInsertData(name, ownername, species, gender, birth, death);

 out.println("<b>Data successfully insert into dataBase</b><BR>");
 out.println("<a href=\"index.jsp\">Return to Index Page</a>");
} else {
 out.println("<b>Please don't leave any text field empty</b><BR>");
 out.println("<a href=\"index.jsp\">Return to Index Page</a>");
}
  } else {
//Fetch data into database
out.println("<html>");
out.println("<head>");
out.println("<title>" + getServletInfo() + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Fetch Data from Database</h1>");
out.println("<table border=\"1\" cellspacing=\
           "2\" cellpadding=\"2\">");
out.println("<thead><tr>");
out.println("<td> Id </td>");
out.println("<td> PetName </td>");
out.println("<td> Ownername </td>");
out.println("<td> species </td>");
out.println("<td> gender </td>");
out.println("<td> Birth </td>");
out.println("<td> Death </td>");
out.println("</thead></tr>");

HibernateDAOClass dao = new HibernateDAOClass();
List<HibernateBean> listBean = dao.getFetchData();
Iterator<HibernateBean> itr = listBean.iterator();
while (itr.hasNext()) {
 HibernateBean hibernateBean = itr.next();
 out.println("<tbody><tr>");
 out.println("<td> " + "<I><b>" 
	  + hibernateBean.getId() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>"
      + hibernateBean.getName() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>"
     + hibernateBean.getOwnername() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>"
     + hibernateBean.getSpecies() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>"
     + hibernateBean.getGender() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>" 
	  + hibernateBean.getBirth() + "</I></b>" + "</td>");
 out.println("<td> " + "<I><b>" 
	  + hibernateBean.getDeath() + "</I></b>" + "</td>");
 out.println("</tr></tbody>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
out.println("<BR><a href=\"index.jsp\">Return to Index Page</a>");
  }
  out.flush(); //free resource
  out.close();
 }
 @Override
 public String getServletInfo() {
  return "r4r.co.in-HibernateServlet";
 }
}

Test Program

/*
 * Save as a HibernateServletMain.java
 * This class is only for test purpose 
(fetch data from database and display over server console)
 */
package r4r.Hibernate.Servlet;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
/**
 *
 * @author R4R
 */
public class HibernateServletMain {

 public static void main(String[] args) {

  Configuration c = new Configuration().configure();
  SessionFactory sf = c.buildSessionFactory();
  Session s = sf.openSession();
  Transaction t = s.beginTransaction();
  try {
Query q = s.createQuery("from HibernateBean");
List<HibernateBean> list = q.list();
// System.out.println("Total result found:"+ list.size());
System.err.printf
	 ("Total (%d) result found into table", list.size());
for (int i = 0; i < list.size(); i++) {
 HibernateBean hBean = list.get(i);
 System.out.println(hBean.getId() + "|" + hBean.getName() 
	           + "|" + hBean.getOwnername() + "|" + hBean.getSpecies()
+ "|" + hBean.getGender() + "|" 
	           + hBean.getBirth() + "|" + hBean.getDeath());
}
  } finally {
t.commit(); //free resource
s.clear();
s.close();
  }
 }
}
Output of Program
Previous Home Next