Friday, September 7, 2012

Struts 2 ,Spring 3, Hibernate 4

Starting with Demo create the project structure as shown below,


before starting please add all required jars for Struts2, Spring3 and Hibernate4,






































Here goes the index page which has the action form has to be submit to struts.xml to perform struts action and validations.
Index.jsp
index.jsp
Hello Struts 2
from index.jsp request goes to the web.xml and from there through DispatureFilter it submitted to struts.xml(Struts-Config.xml)

web.xml 
web.xml
  
Here is the the struts configuration file(Controller of application) having actions and validations inside.

struts.xml
struts.xml
     
struts.xml has a tag called action which is mapped with the jsp form action and then load the class defined in the class attribute and call method defined in method attribute in this case "struts2.web.com.StrutsAction" class and "authenticateEmployee" method. if we dint specified any method then bydefault calls "execute" method.

Here goes the action class,
StrutsAction.java
package struts2.web.com;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import spring.hibernate.EmployeeDao;
import MyDemo.hibernate.Employee;

public class StrutsAction {

    private String message;
    private String userName;
    private String passWord;
    private String passWord1;
   
    private String name;
    private int age;
    private double salary;
   
   
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public StrutsAction() {
    }

    public String authenticateEmployee() {
        /*Resource resource = new FileSystemResource("./src/spring-hibernate.xml");
        BeanFactory factory = new XmlBeanFactory(resource);*/
       
        ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");

       
        EmployeeDao employeeDao = (EmployeeDao)factory.getBean("employeeDao");
       
        Employee empResult = employeeDao.getEmployee(getUserName());
        if(empResult!=null && empResult.getPassword().equalsIgnoreCase(getPassWord())){
            setMessage("Hello " + empResult.getName());
            return "SUCCESS";
        }
        return "ERROR";
    }
   
    public String RegisterEmployee() {
        /*Resource resource = new FileSystemResource("./src/spring-hibernate.xml");
        BeanFactory factory = new XmlBeanFactory(resource);*/
       
        ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");
       
        Employee employee = new Employee();
        employee.setUserID(getUserName());
        employee.setName(getName());
        employee.setAge(getAge());
        employee.setSalary(getSalary());

        EmployeeDao employeeDao = (EmployeeDao)factory.getBean("employeeDao");
       
        Employee empResult = employeeDao.saveOrUpdate(employee);
       
        if(empResult!=null){
            setMessage("Hello " + empResult.getName());
            return "SUCCESS";
        }
        return "ERROR";
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPassWord1() {
        return passWord1;
    }

    public void setPassWord1(String passWord1) {
        this.passWord1 = passWord1;
    }
}

In the authenticateEmployee method we have code call like, which is actually spring configuration calls the spring configuration.
BeanFactory factory = new XmlBeanFactory(resource);
ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");

spring-hibernate.xml
spring-hibernate.xml



HibernateSessionFactory.xml

HibernateSessionFactory.xml

DataSource.xml
DataSource.xml
  
Here we are using "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" which is to map key-variable in .properties file. for that perpose you need to do this entry into the .classpath file. Given below,


database.properties
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;databaseName=HibernateDemo
jdbc.username=sa
jdbc.password=sa

This is upto the configuration,
now for application we are adding one hibernate entity mapping (*.hbm.xml) file


employee.hbm.xml
   
employee.hbm.xml


related entity to this mapping file is,

Employee.java
 package MyDemo.hibernate;

public class Employee {

    private String userID;
    private String password;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public String getUserID(){
        return userID;
    }

    public void setUserID(String userID){
        this.userID = userID;
    }

    public String getPassword() {
        return password;
    }

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

    public String getName(){
        return name;
    }

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

    public int getAge(){
        return age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public double getSalary(){
        return salary;
    }

    public void setSalary(double salary){
        this.salary = salary;
    }

    public String toString(){
        return "Id = " + userID + ", Name = " + name + ", Age = "
            + age + ", Salary = " + salary;
    }
}

Now create one DAO for the accessing this entity through spring,

EmployeeDao.java
package spring.hibernate;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;


import MyDemo.hibernate.Employee;

public class EmployeeDao {

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate
                             hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    public HibernateTemplate getHibernateTemplate(){
        return hibernateTemplate;
    }

    public Employee getEmployee(final String userID){
        HibernateCallback callback = new HibernateCallback() {
            public Object doInHibernate(Session session)
                throws HibernateException,SQLException {
                 Query query = session.createQuery("from Employee");
                List  employees =  query.list();
                //employees.contains(id);
                Iterator iterator = employees.iterator();
                while(iterator.hasNext()){
                    Employee employee = iterator.next();
                    if(employee.getUserID().equalsIgnoreCase(userID)){
                        return employee;
                    }
                }
                return null;
            }
        };
        return (Employee) hibernateTemplate.execute(callback);
    }

    public Employee saveOrUpdate(final Employee employee){
        HibernateCallback callback = new HibernateCallback() {
            public Object doInHibernate(Session session)
                throws HibernateException,SQLException {
                session.saveOrUpdate(employee);
                return  session.load(Employee.class, employee.getUserID());
            }
        };
        return (Employee)hibernateTemplate.execute(callback);
    }
}



Now,  if the struts.xml action tag we have specified the action class in that we are verifying the details with data base through the spring-hibernate configuration, and if we get an "SUCCESS" as a output from the StrutsAction then we redirecting the same request to the success page or if we get an "ERROR" in logging in we forward the same request to the registration.jsp which is registration form for employee. on save of registration we are again saving this information to the database through spring hibernate configuration.


registration.jsp
registration.jsp
Through "gotoStrutsRegistration" we submit this form to struts.xml to registration function defined in the StrutsAction.java

The last one success.jsp, no need to explain more about this one.
success.jsp
success.jsp


Welcome to Struts2
   
       
   
Thank you for the visiting here, for more help or in case of any query please mail me at amol.phasale@gmail.com

Thank you.
 Amol Fasale


   

No comments:

Post a Comment