In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the example analysis of Spring+Hibernate+Struts framework integration. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
SSH framework integration
Some people say that the mainstream framework is still popular now, and SSM has been out for a long time, not to mention SSH. I don't think so. Nowadays, the old project used by many companies is still ssh, which will cost if it is changed to a mainstream framework. In addition, for example, in the part of financial IT, hibernate is recommended in the database layer, because it can be developed quickly, unless it is the Internet, and because it involves high concurrency, mybatis is used in the dao layer, and the data exchange efficiency is fast. Therefore, SSH should not be ignored.
What is SSH
SSH is an integrated framework of struts+spring+hibernate and a popular open source framework for Web applications.
The system integrating SSH framework is divided into four layers in terms of responsibility: presentation layer, business logic layer, data persistence layer and domain module layer to help developers build Web applications with clear structure, good reusability and easy maintenance in a short period of time. Struts is used as the overall infrastructure of the system, responsible for the separation of MVC, in the model part of the Struts framework, control business jump, use the Hibernate framework to support the persistence layer, Spring to manage, manage struts and hibernate. The specific approach is to use the object-oriented analysis method to put forward some models according to the requirements, implement these models as basic Java objects, then write the basic DAO (Data Access Objects) interface, and give the DAO implementation of Hibernate, and use the DAO class implemented by the Hibernate architecture to realize the conversion and access between the Java class and the database. Finally, Spring manages struts and hibernate.
Baidu encyclopedia
Second, the parts involved in SSH
III. Rapid deployment environment
Here we use the small Demo to save the customer to demonstrate the integration of SSH
1. Import the required jar package
1)。 Struts2 framework
* struts-2.3.24\ apps\ struts2-blank\ WEB-INF\ lib\ * .jar-all jar packages required by Struts2
* struts2-spring-plugin-2.3.24.jar-Struts2 integrates the plug-in package of Spring
2)。 Hibernate framework
* hibernate-release-5.0.7.Final\ lib\ required\ * .jar-- jar package required by the Hibernate framework
* slf4j-api-1.6.1.jar-logging API
* slf4j-log4j12-1.7.2.jar-- Log implementation
* mysql-connector-java-5.1.7-bin.jar-the driver package of MySQL
3)。 Spring framework
* IOC core package
* AOP core package
* JDBC templates and transaction core packages
* Spring integrates JUnit test package
* Spring integrates Hibernate core package
* Spring integrates Struts2 core package
2. Configure spring and struts related codes in web.xml
1) configure struts2 core filter
It is defined here as intercepting all
Struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 / *
2) configure spring listeners
When the service starts, the configuration file for spring is loaded first
Org.springframework.web.context.ContextLoaderListener
3) configure the default load path
ContextConfigLocation classpath:applicationContext.xml
Summary: all the code of web.xml is
Org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:applicationContext.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 / *
2. Write relevant configuration files under src
1) spring:applicationContext.xml
Import related constraints
2) hibernate:hibernate.cfg.xml
Import related constraints and configure the database
Com.mysql.jdbc.Driver jdbc:mysql://192.168.174.130:3306/SSH root root org.hibernate.dialect.MySQLDialect true true update org.hibernate.connection.C3P0ConnectionProvider
3) configure log4j.properties
# direct log messages to stdout # # log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d {ABSOLUTE}% 5p% c {1}:% L -% m%n### direct messages to file mylog.log # log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c\: mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j. Appender.file.layout.ConversionPattern=%d {ABSOLUTE}% 5p% c {1}:% L -% m%n### set log levels-for more verbose logging change 'info' to' debug' # log4j.rootLogger=info Stdout
4) struts2:struts.xml
Import related constraints
Summary: the required configuration file for src is shown in the figure
3. Configure the dao layer
Define an interface and its implementation class
Public interface CustomerDao {public void save (Customer customer);} public class CustomerDaoImpl implements CustomerDao {public void save (Customer customer) {}}
4. Define business layer interfaces and implementation classes
Package com.clj.service;import com.clj.domain.Customer;public interface CustomerService {public void save (Customer customer);} package com.clj.service;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * customer's business layer * @ author Administrator * * / public class CustomerServiceImpl implements CustomerService {/ / is used to hold the customer public void save (Customer customer) {}}
5. Define the pojo class
Hibernate manipulates database tables by manipulating pojo classes to achieve object-relational mapping.
Package com.clj.domain;public class Customer {private Long cust_id; private String cust_name; private Long cust_user_id; private Long cust_create_id; private String cust_source; private String cust_industry; private String cust_level; private String cust_linkman; private String cust_phone; private String cust_mobile; public Long getCust_id () {return cust_id;} public void setCust_id (Long cust_id) {this.cust_id = cust_id } public String getCust_name () {return cust_name;} public void setCust_name (String cust_name) {this.cust_name = cust_name;} public Long getCust_user_id () {return cust_user_id;} public void setCust_user_id (Long cust_user_id) {this.cust_user_id = cust_user_id;} public Long getCust_create_id () {return cust_create_id } public void setCust_create_id (Long cust_create_id) {this.cust_create_id = cust_create_id;} public String getCust_source () {return cust_source;} public void setCust_source (String cust_source) {this.cust_source = cust_source;} public String getCust_industry () {return cust_industry;} public void setCust_industry (String cust_industry) {this.cust_industry = cust_industry } public String getCust_level () {return cust_level;} public void setCust_level (String cust_level) {this.cust_level = cust_level;} public String getCust_linkman () {return cust_linkman;} public void setCust_linkman (String cust_linkman) {this.cust_linkman = cust_linkman;} public String getCust_phone () {return cust_phone;} public void setCust_phone (String cust_phone) {this.cust_phone = cust_phone } public String getCust_mobile () {return cust_mobile;} public void setCust_mobile (String cust_mobile) {this.cust_mobile = cust_mobile @ Override public String toString () {return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_user_id=" + cust_user_id + ", cust_create_id=" + cust_create_id + ", cust_source=" + cust_source + ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_linkman=" + cust_linkman + ", cust_phone=" + cust_phone + " Cust_mobile= "+ cust_mobile +"] " }}
6. Define Customer.hbm.xml
This configuration file is related to the pojo class Customer. This file needs to be placed under the same package of the Customer pojo class.
Project construction outline
Fourth, the preservation of demo customer preliminary demonstration
Here, the initial definition of the persistence layer is given to heibernate, the business layer to a struts2, and the creation of an instance to spring
1. Define an interface to save customers and use form form to submit data.
According to the domain name, struts2 wildcard is used for access here.
2. Configure the struts.xml to accept the request, jump to the specified action according to the action name and method, and execute the specified method
Spring integrates struts2 mode 1: action is managed by struts2 framework
* because the imported struts2-spring-plugin-2.3.24.jar package comes with a configuration file struts-plugin.xml, which contains the following code
* Open a constant. If the constant is turned on, then the following constant can be used
* struts.objectFactory.spring.autoWire = name, this constant allows Action classes to automatically assemble Bean objects!
3. Configure the corresponding bean and transactions in the applicationContext.xml of spring
Here, taking advantage of the IOC (inversion of Control) feature in spring, the task of creating an instance is entrusted to the spring framework management.
4. Write the code related to the persistence layer implementation class
Here, using the template class provided by hibernate, the session is internally sealed, so that the methods in session can be called.
/ * * persistence layer * * @ author Administrator * * / public class CustomerDaoImpl implements CustomerDao {/ / Save the data to the database (call the template class (provided by hibernate and encapsulated internally with session)) private HibernateTemplate hibernateTemplate; public void setHibernateTemplate (HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;} / * Save customer * / public void save (Customer customer) {System.out.println ("persistence layer: save customer") HibernateTemplate () .save (customer);}
5. Write the code related to the business layer implementation class.
Package com.clj.service;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * customer's business layer * @ author Administrator * * / @ Transactionalpublic class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao; public void setCustomerDao (CustomerDao customerDao) {this.customerDao = customerDao;} / / used to save customer public void save (Customer customer) {System.out.println ("business layer, save customer") CustomerDao.save (customer);}}
6. Write the code related to action
Here through the template class of struts2
Package com.clj.web.action;import org.apache.struts2.ServletActionContext;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import com.clj.domain.Customer;import com.clj.service.CustomerService;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;/** * customer's control layer * @ author Administrator * * / public class CustomerAction extends ActionSupport implements ModelDriven {/ / Don't forget to manually new private Customer customer=new Customer () Public Customer getModel () {return customer;} / / provides service member attributes and provides the set method private CustomerService customerService; public void setCustomerService (CustomerService customerService) {this.customerService = customerService;} / * Save customer * @ return * / public String add () {System.out.println ("WEB layer, save customer"); / / method 1: create a factory for web (action is created by struts2) WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext (ServletActionContext.getServletContext ()) CustomerService cs= (CustomerService) context.getBean ("customerService"); / / call method cs.save (customer); return NONE;}}
V. Integration of project optimization
1. Spring integrates struts2 mode 2: action is managed by spring framework
Put the specific Action class configuration file applicatonContext.xml in the configuration file, but note: struts.xml needs to be modified
2. Configure the Action class in applicationContext.xml
Note: 1) the default generation of CustomerAction by Spring framework is singleton, while Struts2 framework is multi-instance. So you need to configure scope= "prototype"
2) there is no automatic assembly of struts2 at this time. In action, you need to manually configure the customerService property and generate the set method in the action class.
3 、. Configuration transaction
Spring integrates hibernate mode 1: (configuration file with hibernate.cfg.xml. Emphasis: cannot bind the configuration of the current thread)
In the past, when playing hibernate, hibernate.cfg.xml was managed by the hibernate framework. Its configuration file can generate sessionFactory, and the persistence layer loads this configuration file to obtain sessionFactory, thus creating a factory to generate session, adding, deleting and changing data. At this time, its configuration file should be managed by spring, making full use of the IOC feature of spring.
The Spring framework provides a utility class for HibernateDaoSupport, which DAO can inherit later! Before introducing the hibernate core configuration file, you have to have the dao layer inherit a parent class, HibernateDaoSupport, which encapsulates the transaction template
Look at the source code:
1) modify the corresponding persistence layer implementation class to allow him to inherit HibernateDaoSupport
Package com.clj.dao;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.clj.domain.Customer;/** * persistence layer * inherits HibernateDaoSupport and internally encapsulates HibernateTemplate * @ author Administrator * * / public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {/ / saves the data to the database (call template class (provided by hibernate, internally encapsulated with session) / * private HibernateTemplate hibernateTemplate Public void setHibernateTemplate (HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;} * / / * Save customer * / public void save (Customer customer) {System.out.println ("persistence layer: saving customer"); this.getHibernateTemplate () .save (customer);}}
2) modify the business layer to enable transaction comments
Package com.clj.service;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * customer's business layer * @ author Administrator * * / @ Transactionalpublic class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao; public void setCustomerDao (CustomerDao customerDao) {this.customerDao = customerDao;} / / used to save customer public void save (Customer customer) {System.out.println ("business layer, save customer") CustomerDao.save (customer);}}
3) modify applicationContext.xml file
Introduce the hibernate configuration file first
Configure platform transaction management: used to manage transactions, note that the Hibernate framework is now used, so you need to use the transaction manager of the Hibernate framework
Open transaction comments
Remove the template class configuration and configure sessionFactory for the persistence layer
The full code is as follows
4) modify the action class
Because the business layer implementation class is injected, the business layer method can be called directly at this time without loading the bean
Package com.clj.web.action;import org.apache.struts2.ServletActionContext;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import com.clj.domain.Customer;import com.clj.service.CustomerService;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;/** * customer's control layer * @ author Administrator * * / public class CustomerAction extends ActionSupport implements ModelDriven {/ / Don't forget to manually new private Customer customer=new Customer () Public Customer getModel () {return customer;} / / provides service member attributes and provides the set method private CustomerService customerService; public void setCustomerService (CustomerService customerService) {this.customerService = customerService;} / * Save customer * @ return * / public String add () {System.out.println ("WEB layer, save customer"); / / method 1: create a factory for web (action is created by struts2) / * WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext (ServletActionContext.getServletContext ()) CustomerService cs= (CustomerService) context.getBean ("customerService"); / / call method cs.save (customer); * / customerService.save (customer); return NONE;}}
Spring integrates hibernate mode 2: (configuration file without hibernate.cfg.xml)
Here you are going to delete the core configuration file of hibernate. Before deleting it, you need to configure the relevant contents in its configuration file to the applicatioinContext.xml file of spring.
1. View the relevant contents in the hibernate.cfg.xml file
* basic parameters of database connection (4 major parameters)
* attributes related to Hibernate
* connection pooling
* Mapping file
2. Introduction of configuration
Introduce connection pool
Modify the corresponding sessionFactory: since there is no configuration file for hibernate.cfg.xml, you need to modify the configuration and inject the connection pool
Introduce the object mapping file: because there is no configuration file for hibernate.cfg.xml, it will not be scanned and needs to be injected
Org.hibernate.dialect.MySQLDialect true true update com/clj/domain/Customer.hbm.xml
Now: the full code of applicationContext.xml is as follows
Org.hibernate.dialect.MySQLDialect true true update com/clj/domain/Customer.hbm.xml
Now you can delete the hibernate.cfg.xml file with peace of mind.
In this way, the SSH is integrated.
6. Common methods of Hibernate template
Note: the following code omits the demonstration in the interface (lazy, I believe beginners will understand it)
1) insert:
Persistence layer
Package com.clj.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.clj.domain.Customer;/** * persistence layer * inherits HibernateDaoSupport and encapsulates HibernateTemplate * @ author Administrator * * / public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@ Override public void update (Customer customer) {/ / TODO Auto-generated method stub this.getHibernateTemplate () .update (customer);}}
Business layer
Package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * customer's business layer * @ author Administrator * * / @ Transactionalpublic class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao; public void setCustomerDao (CustomerDao customerDao) {this.customerDao = customerDao;} @ Override public void update (Customer customer) {/ / TODO Auto-generated method stub customerDao.update (customer);}}
Test class
Package com.clj.test;import java.util.List;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.clj.domain.Customer;import com.clj.service.CustomerService / * * A simple way to test the Hiberante template class * @ author Administrator * / @ RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration ("classpath:applicationContext.xml") public class Demo1 {@ Resource (name= "customerService") private CustomerService customerService; / * Test insert * / @ Test public void run1 () {Customer customer=new Customer (); customer.setCust_id (1L); customer.setCust_name ("Test"); customerService.update (customer);}}
2) the following is the specified query, query all, and offline query code
Persistence layer
Package com.clj.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.clj.domain.Customer / * * persistence layer * inherits HibernateDaoSupport and internally encapsulates HibernateTemplate * @ author Administrator * * / public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {/ / saves the data to the database (call template class (provided by hibernate, internally encapsulated with session) / * private HibernateTemplate hibernateTemplate; public void setHibernateTemplate (HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate * / / * Save customer * / public void save (Customer customer) {System.out.println ("persistence layer: saving customer"); this.getHibernateTemplate () .save (customer);} @ Override public void update (Customer customer) {/ / TODO Auto-generated method stub this.getHibernateTemplate () .update (customer) } / * query through primary key * / public Customer getById (Long id) {return this.getHibernateTemplate (). Get (Customer.class, id);} / * query all * / @ Override public List findAll () {String sql= "from Customer"; List list= (List) this.getHibernateTemplate () .find (sql); return list } / * * QBC offline query * / @ Override public List findAllByQBC () {DetachedCriteria criteria=DetachedCriteria.forClass (Customer.class); List list= (List) this.getHibernateTemplate () .findByCriteria (criteria); return list;}}
Business layer
Package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * customer's business layer * @ author Administrator * * / @ Transactionalpublic class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao; public void setCustomerDao (CustomerDao customerDao) {this.customerDao = customerDao;} / / used to save customer public void save (Customer customer) {System.out.println ("business layer, save customer") CustomerDao.save (customer);} @ Override public void update (Customer customer) {/ / TODO Auto-generated method stub customerDao.update (customer);} @ Override public Customer getById (Long id) {/ / TODO Auto-generated method stub return customerDao.getById (id);} @ Override public List findAll () {return customerDao.findAll ();} @ Override public List findAllByQBC () {/ / TODO Auto-generated method stub return customerDao.findAllByQBC ();}}
Test class
Package com.clj.test;import java.util.List;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.clj.domain.Customer;import com.clj.service.CustomerService / * * A simple way to test the Hiberante template class * @ author Administrator * / @ RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration ("classpath:applicationContext.xml") public class Demo1 {@ Resource (name= "customerService") private CustomerService customerService; / * Test insert * / @ Test public void run1 () {Customer customer=new Customer (); customer.setCust_id (1L); customer.setCust_name ("Test"); customerService.update (customer) } / * Test query specified customer * / @ Test public void run2 () {Customer customer=customerService.getById (2L); System.out.println (customer);} / * query all customers * / @ Test public void run3 () {List list=customerService.findAll (); System.out.println (list);} / * QBC (offline query) * / @ Test public void run4 () {List list=customerService.findAllByQBC () System.out.println (list);}}
On the problem of delayed loading of SSH
1. When using deferred loading, the program will throw an exception when querying objects in the WEB layer!
* the reason is that the session object has been destroyed in the business layer before the SQL statement has occurred in delayed loading, so the queried JavaBean object has become a managed object!
* Note: be sure to delete the javassist-3.11.0.GA.jar package first (jar package conflicts)
two。 Solution.
The Spring framework provides a filter for session objects to be created at the WEB layer and destroyed at the WEB layer. You only need to configure the filter
* however: note that it needs to be done before the core filter of struts2 and after the configuration of spring listeners.
OpenSessionInViewFilter org.springframework.orm.hibernate5.support.OpenSessionInViewFilter OpenSessionInViewFilter / *
3. Demonstrate delayed loading
Persistence layer: call the load method, which is loaded late
/ * * delayed loading * / @ Override public Customer loadById (long id) {/ / TODO Auto-generated method stub return this.getHibernateTemplate () .load (Customer.class, id);}
Business layer
@ Override public Customer loadById (long id) {/ / TODO Auto-generated method stub return customerDao.loadById (id);}
Test class
@ Test public void run5 () {Customer customer=customerService.loadById (2L); System.out.println (customer);} this is the end of the article on "sample Analysis of Spring+Hibernate+Struts Framework Integration". I hope the above content can be helpful to you so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.