Рубрики
Без рубрики

Пример интеграции Распорки + Пружина + Гибернация

– Стойки + Пружина + Пример интеграции в спящий режим

В этом учебном пособии вы узнаете, как создать простое веб-приложение для управления клиентами (добавление и выбор), Maven как инструмент управления проектами, Struts 1.x как веб-фреймворк, Spring как фреймворк внедрения зависимостей и Hibernate как фреймворк ORM базы данных.

Общая архитектура интеграции выглядит следующим образом:

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

Чтобы объединить все эти технологии вместе, вам следует..

  1. Интегрируйте Spring с Hibernate с классом Spring ” LocalSessionFactoryBean “.
  2. Интегрируйте пружину со стойками с помощью плагина Spring ready make Struts – ” ContextLoaderPlugIn “.

1. Структура проекта

Это окончательная структура проекта.

2. Сценарий таблицы

Создайте таблицу клиентов для хранения сведений о клиентах.

DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`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. Подробности Maven

Определите все библиотеки зависимостей Struts, Spring и Hibernate в pom.xml . Определите все библиотеки зависимостей Struts, Spring и Hibernate в pom.xml .


  4.0.0
  com.mkyong.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. Зимовать

Ничего особенного не нужно настраивать в режиме гибернации, просто объявите файл и модель сопоставления XML клиента. Ничего особенного не нужно настраивать в режиме гибернации, просто объявите файл и модель сопоставления XML клиента.





    

        
            
            
        
        
            
        
        
            
        
        
            
        
    

Ничего особенного не нужно настраивать в режиме гибернации, просто объявите файл и модель сопоставления XML клиента.

package com.mkyong.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. Весна

Объявление компонентов Spring для бизнес-объекта (BO) и объекта доступа к данным (DAO). Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring ” HibernateDaoSupport “, чтобы легко получить доступ к функции гибернации. Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring “




   	
   		
   	
 
   	
   		
   	


Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring “||HibernateDaoSupport||”, чтобы легко получить доступ к функции гибернации.

package com.mkyong.customer.bo;

import java.util.List;

import com.mkyong.customer.model.Customer;
 
public interface CustomerBo{
 
	void addCustomer(Customer customer);
	
	List findAllCustomer();
 
}

Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring “||HibernateDaoSupport||”, чтобы легко получить доступ к функции гибернации.

package com.mkyong.customer.bo.impl;

import java.util.List;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.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();
	}
}

Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring “||HibernateDaoSupport||”, чтобы легко получить доступ к функции гибернации.

package com.mkyong.customer.dao;

import java.util.List;

import com.mkyong.customer.model.Customer;
 
public interface CustomerDao{
 
	void addCustomer(Customer customer);
	
	List findAllCustomer();
 
}

Класс DAO (CustomerDaoImpl.java ) расширяет класс Spring “||HibernateDaoSupport||”, чтобы легко получить доступ к функции гибернации.

package com.mkyong.customer.dao.impl;

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

import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.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 вместе с помощью ” LocalSessionFactoryBean “. Объявите сведения о базе данных и объедините Spring и Hibernate вместе с помощью “

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

Объявите сведения о базе данных и объедините Spring и Hibernate вместе с помощью “||LocalSessionFactoryBean ||”.


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

	 
  
	
	
	
	
  
 

Объявите сведения о базе данных и объедините Spring и Hibernate вместе с помощью “||LocalSessionFactoryBean ||”.



 


 
    
      
    
 
    
       
         org.hibernate.dialect.MySQLDialect
         true
       
    
 
    
	
          com/mkyong/customer/hibernate/Customer.hbm.xml
	
     	
 


Объявите сведения о базе данных и объедините Spring и Hibernate вместе с помощью “||LocalSessionFactoryBean ||”.


 
	
	
	
 
	
	
	

7. Стойки + Пружина

Чтобы интегрировать Spring со стойками, вам необходимо зарегистрировать встроенный в Spring плагин Struts ” ContextLoaderPlugIn ” в struts-config.xml файл. В классе действий он должен расширять класс Spring ” ActionSupport “, и вы можете получить компонент Spring через getWebApplicationContext() .

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

package com.mkyong.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.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.form.CustomerForm;
import com.mkyong.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");
	  
  }
}

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

package com.mkyong.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.mkyong.customer.bo.CustomerBo;
import com.mkyong.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");
	  
  }
}

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

package com.mkyong.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
	
}

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

#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

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
 




Struts + Spring + Hibernate example

Add Customer

:
:

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
 




Struts + Spring + Hibernate example

List All Customers

Customer NameAddress


Add Customer

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.




 

 
	
		
		
		
		      
		
		
	
	
	

	 

		
 
		
	
		
		
 
		
		
      
 
	
 
 	
 	
		
  	
 

В классе действий он должен расширять класс Spring “||ActionSupport||”, и вы можете получить компонент Spring через ||getWebApplicationContext()||.



 

  Struts Hibernate Examples
 
  
    action
    
        org.apache.struts.action.ActionServlet
    
    
        config
        
         /WEB-INF/struts-config.xml
        
    
    1
  
 
  
       action
       *.do
  


8. Демонстрация

1. Страница списка клиентов Список всех клиентов из базы данных. http://localhost:8080/StrutsSpringExample/ListCustomer.do

2. Добавить страницу клиента Добавьте сведения о клиенте в базу данных. http://localhost:8080/StrutsSpringExample/AddCustomerPage.do

Ссылка

  1. Стойки + Пример пружины
  2. Стойки + Пример гибернации
  3. Пример весны + гибернации

Оригинал: “https://mkyong.com/struts/struts-spring-hibernate-integration-example/”