Struts 2 with Hibernate

Struts 2 with Hibernate


Posted in : Java Posted on : October 1, 2011 at 6:00 PM Comments : [ 0 ]

In this section, you will learn how to integrate Struts 2 with Hibernate.

Struts 2 with Hibernate

In this section, you will learn how to integrate Struts 2 with Hibernate.

In the below example, we will add a record in the database using Hibernate. On addition of a record, all the data stored in the database will show up on the same page(in which you will enter page). You can delete any added record from the same page. The hyperlink is also provided on the same page which redirect us to the home page of the added person in the record.

The hierarchical structure of the project is given below :

The jar files used in the application is given below :

APPLICATION FLOW

First, the following form will appear, in which you need to enter the details of the person whose record you want to add :

When you enter the value, it will add at the bottom table as given below :

As you can see, the table displayed below contains hyperlink of the person's homepage. Here you can delete the record of the person by clicking on the delete hyperlink.

Package Description

PACKAGE DESCRIPTION
com.devmanuals.controller This package contains the java class which act as controller and will get the data from the database table and pass it to the view for presentation.
com.devmanuals.model This class contains the model class.
com.devmanuals.util This package contains the Util file that we use to create connection with hibernate.
com.devmanuals.view This package contains action class.

CODE

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>Contact Manager</display-name>

<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>

</web-app>

index.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<style>
body, input{
font-family: Calibri, Arial;
}
table#contact {
border-collapse: collapse;
width:550px;
}
th {
height: 40px;
background-color: #AAB6B3;
}
</style>
<title>Add New Record</title>
</head>
<body>

<h1>Struts2 Hibernate Example</h1>
<h3>Add New Record</h3>
<s:actionerror/>

<s:form action="add.action" method="post">
<s:textfield name="contact.firstName" label="Firstname"/>
<s:textfield name="contact.lastName" label="Lastname"/>
<s:textfield name="contact.emailId" label="Email"/>
<s:textfield name="contact.cellNo" label="Cell No."/>
<s:textfield name="contact.website" label="Homepage"/>
<s:textfield name="contact.birthDate" label="Birthdate"/>
<s:submit value="Add Contact" align="center"/>

</s:form>


<h2>Records</h2>
<table id="contact" border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Cell No.</th>
<th>Birthdate</th>
<th>Homepage</th>
<th>Delete</th>
</tr>
<s:iterator value="contactList" >
<tr>
<td><s:property value="lastName"/>, <s:property value="firstName"/> </td>
<td><s:property value="emailId"/></td>
<td><s:property value="cellNo"/></td>
<td><s:property value="birthDate"/></td>
<td><a href="<s:property value="website"/>">link</a></td>
<td><a href="delete.action?id=<s:property value="id"/>">delete</a></td>
</tr> 
</s:iterator>
</table>
</body>
</html>

struts.xml

<?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>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />

<package name="default" extends="struts-default" namespace="/">

<action name="add"
class="com.devmanuals.view.ContactAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>

<action name="delete"
class="com.devmanuals.view.ContactAction" method="delete">
<result name="success" type="chain">index.jsp</result>
</action>

<action name="index"
class="com.devmanuals.view.ContactAction">
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
</action>
<action name="index.jsp"
class="com.devmanuals.view.ContactAction">
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
</action>
</package>
</struts>

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>

<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://192.168.10.13/ankdb
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<mapping class="com.devmanuals.model.Contact" />

</session-factory>

</hibernate-configuration>

ContactManager.java

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.devmanuals.model.Contact;
import com.devmanuals.util.HibernateUtil;

public class ContactManager extends HibernateUtil {

public Contact add(Contact contact) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(contact);
session.getTransaction().commit();
return contact;
}

public Contact delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Contact contact = (Contact) session.load(Contact.class, id);
if (null != contact) {
session.delete(contact);
}
session.getTransaction().commit();
return contact;
}

public List<Contact> list() {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Contact> contacts = null;
try {

contacts = (List<Contact>) session.createQuery("from Contact")
.list();

} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return contacts;
}
}

Contact.java

import java.io.Serializable;
import java.sql.Date;

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

@Entity
@Table(name="Contacts")
public class Contact implements Serializable{

private static final long serialVersionUID = -8767337896773261247L;

private Long id;
private String firstName;
private String lastName;
private String emailId;
private String cellNo;
private Date birthDate;
private String website;

private Date created;

@Id
@GeneratedValue
@Column(name="id")
public Long getId() {
return id;
}
@Column(name="firstname")
public String getFirstName() {
return firstName;
}
@Column(name="lastname")
public String getLastName() {
return lastName;
}
@Column(name="email_id")
public String getEmailId() {
return emailId;
}
@Column(name="cell_no")
public String getCellNo() {
return cellNo;
}
@Column(name="birthdate")
public Date getBirthDate() {
return birthDate;
}
@Column(name="website")
public String getWebsite() {
return website;
}
@Column(name="created")
public Date getCreated() {
return created;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public void setCellNo(String cellNo) {
this.cellNo = cellNo;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setCreated(Date created) {
this.created = created;
}
public void setWebsite(String website) {
this.website = website;
}
}

HibernateUtil.java

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

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return 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;
}
}

ContactAction.java

import java.util.List;
import com.devmanuals.controller.ContactManager;
import com.devmanuals.model.Contact;

import com.opensymphony.xwork2.ActionSupport;

public class ContactAction extends ActionSupport {

private static final long serialVersionUID = 9149826260758390091L;
private Contact contact;
private List<Contact> contactList;
private Long id;

private ContactManager linkController;

public ContactAction() {
linkController = new ContactManager();
}
public String execute() {
//if(null != contact) {
//linkController.add(getContact());
//}
this.contactList = linkController.list();
System.out.println(contactList);
System.out.println(contactList.size());
return SUCCESS;
}
public String add() {
System.out.println(getContact());
try {
linkController.add(getContact());
}catch(Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String delete() {
linkController.delete(getId());
return SUCCESS;
}
public Contact getContact() {
return contact;
}
public List<Contact> getContactList() {
return contactList;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public void setContactList(List<Contact> contactsList) {
this.contactList = contactsList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics