Пример интеграции Struts + Spring + Hibernate
Загрузите этот пример Struts 1.x + Spring + Hibernate -Struts-Spring-Hibernate-Example.zip
В этом руководстве вы узнаете, как создать простое веб-приложение для управления клиентами (добавить и выбрать), Maven в качестве инструмента управления проектами, Struts 1.x в качестве веб-платформы, Spring в качестве среды внедрения зависимостей и Hibernate в качестве платформы ORM базы данных.
Общая архитектура интеграции выглядит следующим образом:
Struts (Web page) <---> Spring DI <--> Hibernate (DAO) <---> Database
Чтобы объединить все эти технологии вместе, вы должны ..
-
Интегрируйте Spring с Hibernate с классом Spring «LocalSessionFactoryBean».
-
Интегрируйте Spring со Struts с помощью готового плагина Spring для создания Struts - «ContextLoaderPlugIn».
1. Структура проекта
Это окончательная структура проекта.
2. Настольный скрипт
Создайте таблицу клиентов для хранения данных о клиентах.
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. Maven детали
Определите все библиотеки зависимостей Struts, Spring и Hibernate в 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. зимовать
Ничего особенного настраивать в Hibernate не нужно, просто объявите файл сопоставления XML и модель клиента.
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. весна
Объявление бинов Spring для Business Object (BO) и Object Access Object (DAO). Класс DAO (CustomerDaoImpl.java) расширяет класс Spring «HibernateDaoSupport» для легкого доступа к функции 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); ListfindAllCustomer(); }
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 ListfindAllCustomer(){ 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); ListfindAllCustomer(); }
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 ListfindAllCustomer(){ return getHibernateTemplate().find("from Customer"); } }
6. Весна + Спящий
Объявите детали базы данных и интегрируйте Spring и Hibernate вместе с помощью «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
SpringBeans.xml
7. Struts + Spring
Чтобы интегрировать Spring со Struts, вам необходимо зарегистрировать встроенный плагин Struts «ContextLoaderPlugIn» Spring в файле struts-config.xml. В классе Action он должен расширять класс Spring «ActionSupport», и вы можете получить bean-компонент Spring черезgetWebApplicationContext().
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; Listlist = 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
имя покупателя
Адрес
+ +
struts-config.xml
web.xml
Struts Hibernate Examples action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml 1 action *.do
8. демонстрация
1. List customer page
Список всех клиентов из базы данных.
http://localhost:8080/StrutsSpringExample/ListCustomer.do
2. Add customer page
Добавить сведения о клиенте в базу данных.
http://localhost:8080/StrutsSpringExample/AddCustomerPage.do