Exemple d’intégration Struts Spring Hibernate

Exemple d'intégration Struts + Spring + Hibernate

Téléchargez cet exemple Struts 1.x + Spring + Hibernate -Struts-Spring-Hibernate-Example.zip

Dans ces didacticiels, vous apprendrez à créer une application Web de gestion client simple (ajouter et sélectionner), Maven comme outil de gestion de projet, Struts 1.x comme cadre Web, Spring comme cadre d'injection de dépendance et Hibernate comme cadre ORM de base de données.

L'architecture d'intégration globale ressemble à ceci:

Struts (Web page) <---> Spring DI <--> Hibernate (DAO) <---> Database

Pour intégrer toutes ces technologies ensemble, vous devez ..

  1. Intégrez Spring à Hibernate avec la classe «LocalSessionFactoryBean» de Spring.

  2. Intégrez Spring à Struts via le plug-in Ready Make Struts de Spring - «ContextLoaderPlugIn».

1. Structure du projet

Ceci est cette structure finale du projet.

struts-spring-hibernate-1

struts-spring-hibernate-2

2. Script de table

Créez une table client pour stocker les détails du client.

DROP TABLE IF EXISTS `example`.`customer`;
CREATE TABLE  `example`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

3. Détails de Maven

Définissez toutes les bibliothèques de dépendances Struts, Spring et Hibernate dans pom.xml.
pom.xml


  4.0.0
  com.example.common
  StrutsSpringExample
  war
  1.0-SNAPSHOT
  StrutsExample Maven Webapp
  http://maven.apache.org

  
    
        Java.Net
        http://download.java.net/maven/2/
    

    
        JBoss repository
        http://repository.jboss.com/maven2/
    

  

  

        
    
      org.springframework
      spring
      2.5.6
    

        
      org.springframework
      spring-web
      2.5.6
    

    
      org.springframework
      spring-struts
      2.0.8
    

        
    
      javax
      javaee-api
      6.0
    

        
        
          junit
          junit
          3.8.1
          test
        

        
        
          org.apache.struts
      struts-core
          1.3.10
        

        
          org.apache.struts
      struts-taglib
          1.3.10
        

        
          org.apache.struts
      struts-extras
          1.3.10
        

        
    
      mysql
      mysql-connector-java
      5.1.9
    

    
    
      org.hibernate
      hibernate
      3.2.7.ga
    

    
    
      dom4j
      dom4j
      1.6.1
    

    
      commons-logging
      commons-logging
      1.1.1
    

    
      commons-collections
      commons-collections
      3.2.1
    

    
      cglib
      cglib
      2.2
    
    

    
    
      antlr
      antlr
      2.7.7
    
    

  
  
    StrutsExample
  

4. Hiberner

Rien de bien à configurer dans Hibernate, il suffit de déclarer un fichier de mappage XML client et un modèle.
Customer.hbm.xml



    

        
            
            
        
        
            
        
        
            
        
        
            
        
    

Customer.java

package com.example.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

    private long customerId;
    private String name;
    private String address;
    private Date createdDate;

    //getter and setter methods

}

5. Printemps

Déclaration des beans Spring pour Business Object (BO) et Data Access Object (DAO). La classe DAO (CustomerDaoImpl.java) étend la classe «HibernateDaoSupport» de Spring pour accéder facilement à la fonction Hibernate.
CustomerBean.xml



    
        
    

    
        
    

CustomerBo.java

package com.example.customer.bo;

import java.util.List;

import com.example.customer.model.Customer;

public interface CustomerBo{

    void addCustomer(Customer customer);

    List findAllCustomer();

}

CustomerBoImpl.java

package com.example.customer.bo.impl;

import java.util.List;

import com.example.customer.bo.CustomerBo;
import com.example.customer.dao.CustomerDao;
import com.example.customer.model.Customer;

public class CustomerBoImpl implements CustomerBo{

    CustomerDao customerDao;

    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    public void addCustomer(Customer customer){

        customerDao.addCustomer(customer);

    }

    public List findAllCustomer(){

        return customerDao.findAllCustomer();
    }
}

CustomerDao.java

package com.example.customer.dao;

import java.util.List;

import com.example.customer.model.Customer;

public interface CustomerDao{

    void addCustomer(Customer customer);

    List findAllCustomer();

}

CustomerDaoImpl.java

package com.example.customer.dao.impl;

import java.util.Date;
import java.util.List;

import com.example.customer.dao.CustomerDao;
import com.example.customer.model.Customer;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CustomerDaoImpl extends
       HibernateDaoSupport implements CustomerDao{

    public void addCustomer(Customer customer){

        customer.setCreatedDate(new Date());
        getHibernateTemplate().save(customer);

    }

    public List findAllCustomer(){

        return getHibernateTemplate().find("from Customer");

    }
}

6. Spring + Hibernate

Déclarez les détails de la base de données et intégrez Spring et Hibernate ensemble via «LocalSessionFactoryBean».
database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/example
jdbc.username=root
jdbc.password=password

DataSource.xml



 
   
     WEB-INF/classes/config/database/properties/database.properties
   


  
    
    
    
    
  

HibernateSessionFactory.xml






    
      
    

    
       
         org.hibernate.dialect.MySQLDialect
         true
       
    

    
    
          com/example/customer/hibernate/Customer.hbm.xml
    
     


SpringBeans.xml



    
    
    

    
    

7. Struts + Spring

Pour intégrer Spring à Struts, vous devez enregistrer le plug-in Struts intégré de Spring «ContextLoaderPlugIn» dans le fichier struts-config.xml. Dans la classe Action, il doit étendre la classe «ActionSupport» de Spring, et vous pouvez obtenir le bean Spring viagetWebApplicationContext().

AddCustomerAction.java

package com.example.customer.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import com.example.customer.bo.CustomerBo;
import com.example.customer.form.CustomerForm;
import com.example.customer.model.Customer;

public class AddCustomerAction extends ActionSupport{

public ActionForward execute(ActionMapping mapping,ActionForm form,
    HttpServletRequest request,HttpServletResponse response)
        throws Exception {

    CustomerBo customerBo =
      (CustomerBo) getWebApplicationContext().getBean("customerBo");

    CustomerForm customerForm = (CustomerForm)form;
    Customer customer = new Customer();

    //copy customerform to model
    BeanUtils.copyProperties(customer, customerForm);

    //save it
    customerBo.addCustomer(customer);

    return mapping.findForward("success");

  }
}

ListCustomerAction.java

package com.example.customer.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.springframework.web.struts.ActionSupport;

import com.example.customer.bo.CustomerBo;
import com.example.customer.model.Customer;

public class ListCustomerAction extends ActionSupport{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
    HttpServletRequest request,HttpServletResponse response)
        throws Exception {

    CustomerBo customerBo =
      (CustomerBo) getWebApplicationContext().getBean("customerBo");

    DynaActionForm dynaCustomerListForm = (DynaActionForm)form;

    List list = customerBo.findAllCustomer();

    dynaCustomerListForm.set("customerList", list);

    return mapping.findForward("success");

  }
}

CustomerForm.java

package com.example.customer.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class CustomerForm extends ActionForm {

    private String name;
    private String address;

    //getter and setter, basic validation

}

Customer.properties

#customer module label message
customer.label.name = Name
customer.label.address = Address

customer.label.button.submit = Submit
customer.label.button.reset = Reset

#customer module error message
customer.err.name.required = Name is required
customer.err.address.required = Address is required

add_customer.jsp

Struts + Spring + Hibernate example

Add Customer

:

:

list_customer.jsp

Struts + Spring + Hibernate example

List All Customers

Nom du client

Adresse

+
+

struts-config.xml





    
        

        
              
        

    

    

     

    

        
    

    

        
    
      

    

    
    
        
    

web.xml




  Struts Hibernate Examples

  
    action
    
        org.apache.struts.action.ActionServlet
    
    
        config
        
         /WEB-INF/struts-config.xml
        
    
    1
  

  
       action
       *.do
  

8. Manifestation

1. List customer page
Liste tous les clients de la base de données.
http://localhost:8080/StrutsSpringExample/ListCustomer.do

struts-spring-hibernate-demo-1

2. Add customer page
Ajout des détails du client dans la base de données.
http://localhost:8080/StrutsSpringExample/AddCustomerPage.do

struts-spring-hibernate-demo-2