A sample Hibernate Web Application using Servlets

By: Felix Emailed: 1605 times Printed: 2076 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A Hibernate web application uses Session and Transaction almost like a standalone application. However, some common patterns are useful. You can now write an EventManagerServlet. This servlet can list all events stored in the database, and it provides an HTML form to enter new events.

1. Writing the basic servlet

First we need create our basic processing servlet. Since our servlet only handles HTTP GET requests, we will only implement the doGet() method:

package org.hibernate.tutorial.web;

// Imports

public class EventManagerServlet extends HttpServlet {

protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );

try {
// Begin unit of work
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

// Process request and render page...

// End unit of work
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
catch (Exception ex) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
if ( ServletException.class.isInstance( ex ) ) {
throw ( ServletException ) ex;
}
else {
throw new ServletException( ex );
}
}
}

}

Save this servlet as src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java

The pattern applied here is called session-per-request. When a request hits the servlet, a new Hibernate Session is opened through the first call to getCurrentSession() on the SessionFactory. A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications.

Do not use a new Hibernate Session for every database operation. Use one Hibernate Session that is scoped to the whole request. Use getCurrentSession(), so that it is automatically bound to the current Java thread.

Next, the possible actions of the request are processed and the response HTML is rendered. We will get to that part soon.

Finally, the unit of work ends when processing and rendering are complete. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back. This completes the session-per-request pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern called Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.

2. Processing and rendering

Now you can implement the processing of the request and the rendering of the page.

// Write HTML header
PrintWriter out = response.getWriter();
out.println("<html><head><title>Event Manager</title></head><body>");

// Handle actions
if ( "store".equals(request.getParameter("action")) ) {

String eventTitle = request.getParameter("eventTitle");
String eventDate = request.getParameter("eventDate");

if ( "".equals(eventTitle) || "".equals(eventDate) ) {
out.println("<b><i>Please enter event title and date.</i></b>");
}
else {
createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
out.println("<b><i>Added event.</i></b>");
}
}

// Print page
printEventForm(out);
listEvents(out, dateFormatter);

// Write HTML footer
out.println("</body></html>");
out.flush();
out.close();

This coding style, with a mix of Java and HTML, would not scale in a more complex application-keep in mind that we are only illustrating basic Hibernate concepts in this tutorial. The code prints an HTML header and a footer. Inside this page, an HTML form for event entry and a list of all events in the database are printed. The first method is trivial and only outputs HTML:

private void printEventForm(PrintWriter out) {
out.println("<h2>Add new event:</h2>");
out.println("<form>");
out.println("Title: <input name='eventTitle' length='50'/><br/>");
out.println("Date (e.g. 24.12.2009): <input name='eventDate' length='10'/><br/>");
out.println("<input type='submit' name='action' value='store'/>");
out.println("</form>");
}

The listEvents() method uses the Hibernate Session bound to the current thread to execute a query:

private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {

List result = HibernateUtil.getSessionFactory()
.getCurrentSession().createCriteria(Event.class).list();
if (result.size() > 0) {
out.println("<h2>Events in database:</h2>");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>Event title</th>");
out.println("<th>Event date</th>");
out.println("</tr>");
Iterator it = result.iterator();
while (it.hasNext()) {
Event event = (Event) it.next();
out.println("<tr>");
out.println("<td>" + event.getTitle() + "</td>");
out.println("<td>" + dateFormatter.format(event.getDate()) + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}

Finally, the store action is dispatched to the createAndStoreEvent() method, which also uses the Session of the current thread:

protected void createAndStoreEvent(String title, Date theDate) {
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);

HibernateUtil.getSessionFactory()
.getCurrentSession().save(theEvent);
}

The servlet is now complete. A request to the servlet will be processed in a single Session and Transaction. As earlier in the standalone application, Hibernate can automatically bind these objects to the current thread of execution. This gives you the freedom to layer your code and access the SessionFactory in any way you like. Usually you would use a more sophisticated design and move the data access code into data access objects (the DAO pattern). See the Hibernate Wiki for more examples.

3. Deploying and testing

To deploy this application for testing we must create a Web ARchive (WAR). First we must define the WAR descriptor as src/main/webapp/WEB-INF/web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
<servlet-name>Event Manager</servlet-name>
<servlet-class>org.hibernate.tutorial.web.EventManagerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Event Manager</servlet-name>
<url-pattern>/eventmanager</url-pattern>
</servlet-mapping>
</web-app>

To build and deploy call mvn package in your project directory and copy the hibernate-tutorial.war file into your Tomcat webapps directory.

Note: If you do not have Tomcat installed, download it from http://tomcat.apache.org/ and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration.

Once deployed and Tomcat is running, access the application at http://localhost:8080/hibernate-tutorial/eventmanager. Make sure you watch the Tomcat log to see Hibernate initialize when the first request hits your servlet (the static initializer in HibernateUtil is called) and to get the detailed output if any exceptions occurs.


Hibernate Home | All Hibernate Tutorials | Latest Hibernate Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

tnx

View Tutorial          By: arion at 2011-06-03 01:24:30

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Felix
Hibernate JDBC and Connection Properties
Hibernate Transaction Properties
Hibernate Cache Properties
Hibernate Configuration Properties
Creating Connection Pool for JDBC Connections in Hibernate
SessionFactory in Hibernate
Programmatic configuration in Hibernate
Contextual sessions in Hibernate
Some Basic APIs in Hibernate
A sample Hibernate Web Application using Servlets
Step by Step Hibernate - Your First Hibernate Application
Tutorial Using the Java Persistence API (JPA) in Hibernate
Download Hibernate latest version

More Tutorials in Hibernate
Fetching strategies in Hibernate
equals() and hashCode() in Hibernate
Tuplizers (org.hibernate.tuple.Tuplizer) in Hibernate
EntityNameResolvers in Hibernate
Hi/lo algorithm in Hibernate
Identity columns and sequences in Hibernate
Assigned identifiers in Hibernate
Primary keys assigned by triggers in Hibernate
Formula in Hibernate
Step by Step Hibernate - Your First Hibernate Application
A sample Hibernate Web Application using Servlets
Some Basic APIs in Hibernate
Contextual sessions in Hibernate
Programmatic configuration in Hibernate
SessionFactory in Hibernate

More Latest News
Most Viewed Articles (in Hibernate )
Hibernate Vs. JDBC ( A comparison)
Tuplizers (org.hibernate.tuple.Tuplizer) in Hibernate
Tutorial Using the Java Persistence API (JPA) in Hibernate
A sample Hibernate Web Application using Servlets
Fetching strategies in Hibernate
Assigned identifiers in Hibernate
Delta Electronics Chairman Bruce Cheng Endows NCKU Build Y.S. Sun Green Building Research Center
Step by Step Hibernate - Your First Hibernate Application
Types of inheritence models in Hibernate
What is component mapping in hibernate?
Paging Through the Result Set in Hibernate
Download Hibernate latest version
Some Basic APIs in Hibernate
Contextual sessions in Hibernate
Programmatic configuration in Hibernate
Most Emailed Articles (in Hibernate)
Hibernate Vs. JDBC ( A comparison)
Hibernate Transaction Properties
Tuplizers (org.hibernate.tuple.Tuplizer) in Hibernate
Programmatic configuration in Hibernate
EntityNameResolvers in Hibernate
Delta Electronics Chairman Bruce Cheng Endows NCKU Build Y.S. Sun Green Building Research Center
Step by Step Hibernate - Your First Hibernate Application
What is component mapping in hibernate?
Paging Through the Result Set in Hibernate
Tutorial Using the Java Persistence API (JPA) in Hibernate
A sample Hibernate Web Application using Servlets
Creating Connection Pool for JDBC Connections in Hibernate
Hibernate Configuration Properties
Download Hibernate latest version
Contextual sessions in Hibernate