Friday, 6 July 2012

Struts2 with Hibernate Integration in netbeans

according to my previous post ContactDetails application Struts 2 Example Step by Step in net beans next step is connect my sql data base using hibernate.
Create the database name logintest in mysql and create the table CONTACTS
CREATE TABLE CONTACTS
(  
    id      INT PRIMARY KEY AUTO_INCREMENT,
    firstname   VARCHAR(45),
    lastname    VARCHAR(45),
    cell_no     VARCHAR(15),
    email_id    VARCHAR(50),
    website     VARCHAR(150),
    birthdate   DATE,
    created     TIMESTAMP DEFAULT NOW()
);

add some jar files given below.
next step Create the necessary packages inside the src directory.
contact.action. this package contain the ContactAction.java file
contact.controller. this Package Contain ContactController.java file
sandy.model. this package contain two java file Contact.java ,ContactHibernateUtil.java and one xml file contact.hbm.xml for hibernate mapping

next step Create hibernate.cfg.xml file in src folder . and copy the code 
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/logintest</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">hrlabz</property>
        <property name="connection.pool_size">1</property>
        
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">
            org.hibernate.cache.NoCacheProvider
        </property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping resource="sandy/model/contact.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
next step Create the new package package name sandy,model  inside the sandy.model package create new java  class Contact this class already in my previous post 
Contact.java 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sandy.model;

import java.sql.Date;

/**
 *
 * @author sandy
 */
public class Contact {
    private int id;
    private String firstName;
    private String lastName;
    private String emailId;
    private String cellNo;
    private Date birthDate;
    private String website;
    private Date created;

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getCellNo() {
        return cellNo;
    }

    public void setCellNo(String cellNo) {
        this.cellNo = cellNo;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public int getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    } 
}
next step Create contact.hbm.xml file inside the sandy.model package. 
contect.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="sandy.model.Contact" table="contacts">
   <id name="id" type="int" column="id" >
    <generator class="increment"></generator>
    </id>   
    <property name="firstName" column="firstname"></property>
    <property name="lastName" column="lastname"></property>
     <property name="cellNo" column="cell_no"></property>
    <property name="emailId" column="email_id"></property>
     <property name="birthDate" column="birthdate"/>
    <property name="website" column="website"/> 
      </class>
</hibernate-mapping>

 next step Create the contactHibdernateutil.java class inside the sandy.model package.  that we use to create connection with hibernate.
 ContactHibernateUtil.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sandy.model;

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

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author sandy
 */
public class ContactHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
next to create the Contactcontroller. java file inside the contact.controller package. it class handle the hibernate transaction like save data restive data from data base.
 Contactcontroller. java 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contact.controller;

import java.util.List;
import org.hibernate.Session;
import sandy.model.Contact;
import sandy.model.ContactHibernateUtil;

/**
 *
 * @author sandy
 */
public class ContactController {
    
 private Session session=ContactHibernateUtil.getSessionFactory().getCurrentSession();
    
    public Contact Add(Contact contact)
    {
        try{
        session.beginTransaction();
        session.save(contact);
        session.getTransaction().commit();
        }catch(Exception e)
                {
                
                }
    return contact;
    
    }
    public List<Contact> list()
    {
        List<Contact> contactlist=null;
        try{
    
    session.beginTransaction();
    
    contactlist=(List<Contact>) session.createQuery("from Contact").list();
    session.getTransaction().commit();
        } catch(Exception e)
    {
        
        
    }
        return contactlist;
    }
}
next step create action class inside the  contact.action package ContactAction.java that class handle the client request and render the view page  and send the client data to the Contactcontroller.
ContactAction.java

package contact.action;

import com.opensymphony.xwork2.ActionSupport;
import contact.controller.ContactController;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import sandy.model.Contact;
import sandy.model.ContactHibernateUtil;

/**
 * 
 *
 * @author sandy
 */
public class ContactAction extends ActionSupport{
    private Contact contact;
private List<Contact>listcontact;
private  ContactController controller;
public ContactAction()
{
controller=new ContactController();
}
    public Contact getContact() {
        return contact;
    }

    public List<Contact> getListcontact() {
        return listcontact;
    }

    public void setListcontact(List<Contact> listcontact) {
        this.listcontact = listcontact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }
    public String execute()
    {

    listcontact= controller.list();
        return SUCCESS;
    }
    public String add()
    {

       contact= controller.Add(getContact());
        listcontact=controller.list();
        
         return SUCCESS;
    }
    
}
next we create the the jsp file for input the data and display the data . first create new folder inside web page directory  jspView . inside jspView folder create new jsp file contactDetails.jsp.
 
contactDetails.jsp.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        
        <h1>Hello World!</h1>
         <s:form action="add" method="post">
             <s:textfield name="contact.firstName" label="First Name"/>
             <s:textfield name="contact.lastName" label="Last Name"/>
             <s:textfield name="contact.emailId" label="Email"/>
             <s:textfield name="contact.cellNo" label="mobile no"/>
             <s:textfield name="contact.website" label="website"/>
             <s:textfield name="contact.birthDate" label="DOB"/>
  
             <s:submit  name="submit" align="center" value="submit"/>

        </s:form>
        <h2>Contacts</h2>
<table border="2">
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Cell No.</th>
    <th>Birthdate</th>
    <th>Homepage</th>
    
</tr>

<tr>
        <td><s:property value="contact.firstName"/> <s:property value="contact.lastName"/> </td>
        <td><s:property value="contact.emailId"/></td>
        <td><s:property value="contact.cellNo"/></td>
        <td><s:property value="contact.birthDate"/></td>
        <td><a href="<s:property value="contact.website"/>">link</a></td>
       
    </tr>
    
</table>
        <table border="2">
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Cell No.</th>
    <th>Birthdate</th>
    <th>Homepage</th>
   
</tr>
<s:iterator value="listcontact" var="contact">
    <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>
        
    </tr>
</s:iterator>
</table>
    </body>
</html>


next step we create struts.xml file inside the src folder in default package  
struts.xml

<!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="contact" class="contact.action.ContactAction">
        <result>jspView/contactDetails.jsp</result>
    </action>
    <action name="add" class="contact.action.ContactAction" method="add">
       <result name="input">jspView/contactDetails.jsp</result>
       <result name="success">/jspView/contactDetails.jsp</result>
        
    </action>
    </package>
</struts>
web .xml file

<?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">
    <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>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>jspView/contactDetails.jsp</welcome-file>
    </welcome-file-list>
</web-app>

deploy the application on tomcate server  and type the url http://localhost:8080/ ContactDetail 
and see the ouput  like .


1 comment: