Srikanth Technologies

Using Struts2 and Hibernate

In this blog I show a simple example to demonstrate how to use Struts2 with Hibernate. We use a simple registration page to take details from user and insert those details using Hibernate into Oracle database.

The blog covers the following :

In case you are not familiar with Struts2, please read my blog on Getting Started With Struts2 first and then the following.

Create a new web application using your favourite IDE. Make sure you create or modify the following files as shown below. Here I show where the files are to be placed in the web application. You need to place them in your IDE according to structure of your IDE. For example, all classes are to be placed in WEB-INF/classes in web application, but in NetBeans you need to place classes in Source Packages node (of course they are ultimately placed into WEB-INF/classes by NetBeans).

web.xml

Deployment descriptor, which is placed under WEB-INF, is used to configure filter related to Struts2 as follows:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>registeruser.jsp</welcome-file>
    </welcome-file-list>
</web-app>

hibernate.cfg.xml

Place hibernate configuration file classes folder under WEB-INF/classes as follows. It is configured to access Oracle10g with HR account. It also uses a single entity called User, which is in entities package.


<?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.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping class="entities.User"/>
  </session-factory>
</hibernate-configuration>

struts.xml

Struts2 configuration file is used to specify the action classes and URLs to be invoked based on the string returned by execute() method in action class. Action class is placed in  WEB-INF/classes/actions  folder. However you can place action class in any package you like.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action  name="register" class="actions.RegisterAction">
            <result name="success">registercomplete.jsp</result>
            <result name="fail">registerfail.jsp</result>
        </action>
    </package>
</struts>

User class

User class is an entity that is mapped to Users table in Oracle database. Field userid is declared as Id and its value is automatically generated. We are using annotations to provide metadata regarding class and fields.

This is placed in WEB-INF/classes/entities folder.

package entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name="users")
public class User {
    @Id
    @GeneratedValue ( strategy =  GenerationType.AUTO)
    private int userid;
    private String email;
    private String password;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

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

    public int getUserid() {
        return userid;
    }
    
    public void setUserid(int userid) {
        this.userid = userid;
    }
}

HibernateUtil class

This class is used to create and return a single instance of SessionFactory. It uses AnnotationConfiguration class so that annotations are supported by Hibernate. Static initializer is used to create an object of SessionFactory and getSessionFactory() method to return it.

Place it in WEB-INF/classes/dao folder.

package dao;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

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

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

UserDAO class

This is used to access Hibernate from Struts2 action. It is based on Data Access Object design pattern.

This is placed in WEB-INF/classes/dao folder.


package dao;

import entities.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


public class UserDAO {

    public static boolean registerUser(User u) {

         SessionFactory sf = HibernateUtil.getSessionFactory();
         Transaction t = null;
         try  {
         Session s  = sf.openSession();
         t = s.beginTransaction(); // start a new transaction
         s.persist(u);
         t.commit();  // commit transaction  
         return true;
         }
         catch(Exception ex) {
             System.err.println("Error -->"  + ex.getMessage());
             if ( t!=null) t.rollback();  // rollback transaction on exception 
             return false;
         }
    }
}

RegisterAction class

This is the action class in Struts2. It uses UserDAO and User entity to insert a row into User table through Hibernate.

Place it in WEB-INF/classes/actions folder.

package actions;

import dao.UserDAO;
import entities.User;

public class RegisterAction {

    private String email,pwd;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public RegisterAction() {
    }

    public String execute() throws Exception {
        
        // create an object of User entity
        User u = new User();
        u.setEmail(email);
        u.setPassword(pwd);
        
        if ( UserDAO.registerUser(u))   // Access persistence tier through DAO
             return "success";
        else
            return "fail";
    }
}

registeruser.jsp

This is used to take information from user using struts2 user interface components.

This is placed in root directory of the application.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
    <head>
       <title>User Registration </title>
    </head>
    <body>
        <h2>User Registration</h2>
        <s:form action="register">
            <s:textfield name="email" label="Enter email address : "/>
            <s:password name="pwd" label="Enter your password : " />
            <s:submit value="Register" />
        </s:form>
    </body>
</html>

registercomplete.jsp and registerfail.jsp

These two JSPs are called depending on the result of the action. There JSPs are listed in struts.xml.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <body>
        <h1>Registration Completed Successfully!</h1>
    </body>
</html>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <body>
        <h1>Registration Failed!</h1>
        <a href="registeruser.jsp">Try Again </a>
    </body>
</html>

Directory Hierarchy

The following is the directory hierarchy of the entire web application.

struts2hibernate
    registeruser.jsp
    registercomplete.jsp
    registerfail.jsp
    WEB-INF
        web.xml
        classes
           hibernate.cfg.xml
           struts.xml
           entities
              User.class
           dao
              HibernateUtil.class
              UserDAO.class
           actions
              RegisterAction.class
        lib
            oracle driver
            struts2 related jar files
            Hibernate related jar files

In case you are using NetBeans IDE then at the time of creating web application select Hibernate and Struts2 (first you need to install Struts 2 plugin) options in Frameworks step. As a result NetBeans automatically includes all the necessary .jar files to project.

Deploy the application to any Java EE Web Container (such as Tomcat) and invoke registeruser.jsp from brower. Enter data into text boxes and click on submit button to insert a row into users table in Oracle database.