SSH Framework Online Mall project integration of the 1th war Struts2, Hibernate4.3 and Spring4.2_java

Source: Internet
Author: User
Tags aop rollback sessions ssh create database tomcat server

This article began to do an online mall project, first from the setting up environment, step-by-step integration s2sh. This blog post mainly summarizes how to integrate Struts2, Hibernate4.3 and Spring4.2.

The integration of the three major framework to start from the construction of various parts of the environment, that is, first of all, to spring,hibernate and STRUTS2 environment, to ensure that they have no problems, and then do integration. This blog post follows the following sequence: Build the spring environment--> then build the hibernate environment--> integrate spring and hibernate--> build STRUTS2 environment--> integrate spring and Struts2.

1. Management of the entire project jar package

Spring has a lot of jar packages, it is recommended that they be divided into classes, and then added to the user Library, which is easy to manage, also at a glance. Here's a summary of the basic jar packages needed for the entire SSH, looking at the following figure:


As you can see from the diagram, Spring's jars are first grouped into four categories: Spring-4.2.4-core, SPRING-4.2.4-AOP, Spring-4.2.4-persistence, and Spring-4.2.4-web. Put spring's core packages into the cores, and AOP-related is put into AOP, associated with persistence (and hibernate consolidation) in persistence, and web (with struts2 consolidation) in the Web. What jar packages are there in each section? Take a look at the screenshot below:


Note: in each of these categories, the package does not contain all the jars in the original package, some jar files are not used, and so on when the specific project needs to add to the line, the above image is to ensure that the project environment can be built to build the most basic jar package.

2. Setting up the spring environment

The above jar package screenshot is the final integration of all the jar package, just start to build the environment does not need to add all at once, you can add 1.1, this is also more conducive to understanding the role of each part of the jar package, of course, all of which are added to it is also possible.

2.1 Add profile Beans.xml and corresponding jar packages

Create a new project and add your own library to the user library, where you add two, namely Spring-4.2.4-core and SPRING4.2.4-AOP, and add jar packs no longer repeat. After the addition, in the SRC directory to add beans.xml files, the template of this file a lot of online, spring from the example also have, a test come over the line, see the following figure:


2.2 Test Spring's IOC environment

Let's write a common Java class Java.util.Date class to test whether the spring IOC is normal, and if it is injected properly in the test program, then the spring IOC environment is built successfully, so let's write a test case:

/** 
 * @Description TODO (with spring annotation debugging, only supports Spring3.1 and above) 
 * @author Ni Shengwu 
 * 
 * * * * * * After Spring3.1 a Spring-test-4.2.4.release.jar package, which is specifically designed to support JUnit-based testing, the jar package is in Spring-4.2.4-core 
 There is a springjunit4classrunner.class in the jar bag, add it with @runwith annotation 
 * 
 * Annotation @contextconfiguration means to inject the ApplicationContext object into the test program as it did before, using the 
 * 
/@RunWith directly ( Springjunit4classrunner.class) 
@ContextConfiguration (locations= "Classpath:beans.xml") Public 
class sshtest { 
 
 @Resource 
 private date date; 
 
 @Test//test development environment for spring IOC public 
 void Springioc () { 
 System.out.println (date); 
 } 
 

Finally the normal output: Thu Apr 22:45:13 CST 2016. Shows that the date object has been injected into spring to verify that the spring IOC functions properly, and that spring's environment is built to complete.

3. Build Hibernate environment

The hibernate environment is more complicated than spring because it uses reverse engineering in MyEclipse. We build the hibernate development environment according to the following steps:

3.1 Add the appropriate jar package

This is mainly to add two jar packages to the user library: hibernate4.3.11 and MySQL driver package mysql-connector-java-5.1.26, no longer repeat.

3.2 New databases and tables

Drop database if exists shop; 
Create DATABASE shop default character set UTF8; 
Use shop; 
drop table if exists category; 
CREATE TABLE Category 
(/ 
 * category number, auto Grow */ 
 ID int NOT NULL auto_increment,/ 
 * category name 
 /type varchar ( 
 /* category is a hot category, the hotspot category can be displayed on the home * * HOT 
 bool Default false, 
 /* Set category number for the main key * * * * 
 PRIMARY KEY (ID) 
); 

3.3 DB Browser connects to MySQL database

DB browser refers to the MyEclipse in a view window, can be very intuitive to see what the MySQL database and tables, open the DB browser method: Window->open perspective->db Browser opens the DB Browser Working window. If you do not have a DB Browser, follow the following: Window->show view->other-> input db Browser, find it open.

After opening, we started to connect to the MySQL database, the db browser window in the margin of the right key->new, will pop up the following dialog box:

After filling in, click Test driver testing, the test by means that the database connection driver has been configured, and then finish, This allows us to see the database MySQL5.6 in the DB browser window, and right-click to see the existing libraries and tables in the database, as follows:


3.4 Creating XML mapping files and Sessionfactory

Sessionfactory is used to create the session, we create it by: Project name right button->myeclipse->add Hibernate capabilities, if no ADD Hibernate capabilities, click Project Facets->install Hibernate Facets, the following window will pop up:

Next, add Hibernate Support to the MyEclipse, Hibernate.cfg.xml mapping files and sessionfactory. This is mainly for sessionfactory to build a package, the default package is not.

Next, add the driver, because we have already configured a driver, so here directly select just configure the right.

Next, since we've added our own jar reservations before, here's no choice, just finish.

        So we have completed the creation of the Hibernate configuration file and Sessionfactory. Let's take a quick look at what's inside the Sessionfactory created by MyEclipse:

public class Hibernatesessionfactory {private static final threadlocal<session> ThreadLocal = new threadlocal& Lt Session> (); Sessionfactory is the use of thread pooling technology private static org.hibernate.SessionFactory sessionfactory; 
 Sessionfactory: Create session of the factory private static Configuration Configuration = new Configuration (); 
 
 private static Serviceregistry serviceregistry; 
 Initialize sessionfactory try {configuration.configure () when the static {//class loads; Serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()). BuildServiceRegistry ( 
 ); Sessionfactory = Configuration.buildsessionfactory (serviceregistry); Sessionfactory in Hibernate4 method} catch (Exception e) {System.err.println ("%%%% Error creating Sessionfactory") 
 ; 
 E.printstacktrace (); Hibernatesessionfactory () {//private constructor prevents new objects from being created, guaranteeing Sessionfactory single instance} public static session getsession ( Throws Hibernateexception {Session sessions = (session) Threadlocal.get ()//take s from the thread poolEssion if (session = NULL | |!session.isopen ()) {//If thread pool is empty, or session open failure if (sessionfactory = null) {Rebuilds Essionfactory (); If the sessionfactory is empty, then create again, the same as the static part of the session = (sessionfactory!= null)? Sessionfactory.opensession (): null; Sessionfactory is not empty to create a session threadlocal.set (session); 
 Then put the session in the thread pool, next time to get back to the session; 
 public static void Rebuildsessionfactory () {try {configuration.configure (); Serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()). BuildServiceRegistry ( 
 ); 
 Sessionfactory = Configuration.buildsessionfactory (serviceregistry); 
 catch (Exception e) {System.err.println ("%%%% Error creating Sessionfactory%%%%"); 
 E.printstacktrace (); 
 The public static void CloseSession () throws Hibernateexception {The Session sessions = (session) Threadlocal.get (); 
 
 Threadlocal.set (NULL); 
 if (session!= null) {session.close (); }} public static ORG.HIBERNATE.SEssionfactory getsessionfactory () {//provides a public interface for external access to this single example sessionfactory return sessionfactory; 
 public static Configuration GetConfiguration () {return Configuration;  } 
 
}

As can be seen from the creation of the Hibernatesessionfactory, the main use of the single case mode and thread pool technology. It is not difficult to understand.

3.5 Generate model, ORM mapping file through reverse engineering

The following starts with reverse engineering to create an instance object, which is the database table corresponding to model. Right-click the table shop we just created in the DB Browsera window, select Hibernate Reverse engineering start creating:

There are two ways to create, based on the configuration file and based on the annotation, the specific view of the developer mood, you can choose:

Next, select the native primary key self-enhancement method, and then complete the reverse engineering creation model and ORM mapping.

When finished, there will be a category model build, and a corresponding mapping will be generated in the Hibernate.cfg.xml file, which is different from the one based on the configuration file and the annotation generated in hibernate.cfg.xml.

3.6 Test Hibernate Persistent Database

Because there is no integration with spring, but simply to build the hibernate development environment, so we do not need to use annotations, we through a direct new service to perform data warehousing.

First write Categoryservice interface and implementation class:

Public interface Categoryservice {public 
 void Save (Category Category);//To test the hibernate environment 
} public 
 
class Categoryserviceimpl implements Categoryservice { 
 
 @Override//Not and spring consolidation situation public 
 void Save (Category category) { 
 //through the sessionfactory just generated to get the session sessions session 
 = Hibernatesessionfactory.getsession (); 
 try { 
 //manual transaction 
 session.gettransaction (). Begin (); 
 Execute business logic 
 session.save (category); 
 Manually submit 
 Session.gettransaction (). commit (); 
 } catch (Exception e) { 
 session.gettransaction (). Rollback (); 
 throw new RuntimeException (e); 
 } finally { 
 hibernatesessionfactory.closesession ();}}} 
 

The following tests are added to hibernate in the test case just now:

@RunWith (Springjunit4classrunner.class) 
@ContextConfiguration (locations= "Classpath:beans.xml") 
public Class Sshtest { 
 
 @Resource 
 private date date; 
 
 @Test//test development environment for spring IOC public 
 void Springioc () { 
 System.out.println (date); 
 } 
 
 @Test//test Hibernate development environment, because there is no consolidation, you can direct new public 
 void Hihernate () { 
 Categoryservice categoryservice = new Categoryserviceimpl (); 
 Category Category = new Category ("Men's Leisure", true); 
 Categoryservice.save (category); 
 } 
 

We looked at the database and found that we had just inserted this item to show that there was no problem with the hibernate environment. At this point, hibernate development environment we have built.

4. Integrate spring and Hibernate

Having built the development environment for spring and hibernate, we started to integrate both. After you've consolidated spring and hibernate, you can use AOP to let Spring manage hibernate transactions. The integration of spring and hibernate mainly from two aspects, one is to import the necessary jar package, and the second is to configure Beans.xml files. Here's a step-by-step integration of spring and hibernate.

4.1 Import the appropriate jar package

The jar packages that need to be imported when you integrate spring and hibernate have two chunks, spring4.2.4-persistence and c3p0-0.9.5.1, and the specific jar files in each jar package are shown in the screenshot above, which is no longer detailed here. The following starts the configuration of the Beans.xml file.

4.2 Configuration Data Source DataSource

First configure the DataSource, then the corresponding part of the hibernate.cfg.xml can be killed. Because it is configured in spring, Spring will initialize the DataSource, which means that it is done by spring, and the corresponding part of the hibernate.cfg.xml can be erased. As follows:

<!--Com.mchange.v2.c3p0.ComboPooledDataSource class--> <bean ID in C3p0-0.9.5.1.jar package com.mchange.v2.c3p0 package 
= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > 
 <property name= "Driverclass" Com.mysql.jdbc.Driver "/> 
 <property name= 
 jdbcurl" value= "Jdbc:mysql://localhost:3306/shop"/> <property name= "User" value= "root"/> <property name= "password" value= " 
 root"/> 

Parts of the hibernate.cfg.xml that need to be killed:


4.3 Configuration Sessionfactory

Configuration sessionfactory is used to generate a session, and the other hibernatetemplate can, but the sessionfactory is used instead of hibernatetemplate, Because Hibernatetemplate is provided by spring, it relies on spring, and if you don't need spring for a day, you'll get an error. And Sessionfactory is provided by hibernate, no problem. Hibernatetemplate's dependence is too strong. Let's look at the specific configuration:

<!-- Org.springframework.orm.hibernate4.LocalSessionFactoryBean classes in Spring-orm-4.2.4.release.jar packs of Org.springframework.orm.hiberna --> <bean id= "sessionfactory" class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" in Te4 package 
> 
 <property name= "DataSource" ref= "DataSource"/> <property name= "Configlocation" 
 Classpath:hibernate.cfg.xml "/> <!--load Hibernate profile--> 
</bean> 

Sessionfactory in the DataSource we use just the DataSource, ref attribute reference to come in, configlocation we are not in this match, Loading the Hibernate.cfg.xml file directly, using the configuration in the Hibernate configuration file, is more concise and convenient.

4.4 Configuration Transaction Manager

The configuration transaction manager is used to manage sessionfactory so that all sessions generated by Sessionfactory will have declarative management. The configuration is as follows:

<!-- Org.springframework.orm.hibe of Org.springframework.orm.hibernate4.HibernateTransactionManager class Spring-orm-4.2.4.release.jar package --> 
<bean id= "TransactionManager" class= "in Rnate4 package Org.springframework.orm.hibernate4.HibernateTransactionManager "> 
 <property name=" sessionfactory "ref=" Sessionfactory "/> 
</bean> 

Again, sessionfactory we use the sessionfactory that we just configured, we can use the ref attribute reference to come in. Here will be found, from the above has been matched down, are a series of operations, a reference down.

4.5 Configuration Advice (notification)

The purpose of configuring advice is to specify which methods require what type of transaction mode. See Configuration:

<tx:advice id= "Advice" transaction-manager= "TransactionManager" > 
 <tx:attributes> 
 <tx: Method Name= "save*" propagation= "REQUIRED"/> <tx:method name= "update*" 
 propagation= "REQUIRED"/> 
 <tx:method name= "delete*" propagation= "REQUIRED"/> <tx:method " 
 *" Name= "propagation=" SUPPORTS 
 </tx:attributes> 
</tx:advice> 

Required indicates that if a transaction exists, the current transaction is supported, and if no new transaction is created, the transaction pattern is applied to all methods that begin with Save, update, and delete, which means that transaction support needs to be added when adding or deleting the database. Supports indicates that if a transaction exists, the current transaction is supported, if not.

4.6 Configuring AOP Slices

 <aop:config> <!--configure which packages of classes to cut into a transaction--> <aop:pointcut id= "Pointcut" express ion= "Execution (* cn.it.shop.service.impl.*.* (..))"/> <aop:advisor advice-ref= "Advice" pointcut-ref= "Pointcut" "/><!--connected to the <span style=" Font-family:microsoft Yahei; " 
> </span> face of the advice and above Pointcut--> <!--aop:pointcut to write on the aop:advisor above, otherwise it will be an error--> </aop:config> 

AOP is the aspect-oriented programming, Aop:pointcut defines a slice, and the configuration in the expression attribute means all the methods under the Cn.it.shop.service.impl package, regardless of the return value and parameters, are cut into the transaction. The package belongs to the DAO layer and operates directly on the database. Aop:advice to combine the notice with the cut, we use the advice and pointcut that are configured directly above to bring it in. This configuration is good, meaning that all Cn.it.shop.service.impl package methods need to cut into the transaction management, specifically, save, update, delete the beginning of the method to use the Requied way, other methods using the Supports method. This is a good way to understand the meaning of this configuration.
4.7 Test Consolidation Results
before setting up the hibernate environment, we tested a new service to manipulate the database, because there was no integration with spring. Now, by configuring Beans.xml, let Spring manage hibernate transactions, so now the test is to give the service to spring management, through spring injection, and rely on sessionfactory, if you can insert data into the database, then declare the transaction OK.
First, we're going to match this service in the spring's configuration file Beans.xml:

Copy Code code as follows:
<bean id= "Categoryservice" class= "Cn.it.shop.service.impl.CategoryServiceImpl" >
<property name= "Sessionfactory" ref= "sessionfactory"/><!--dependent sessionfactory with the sessionfactory--> we had before.
</bean>



Second, we need to add a method to test the integration after the Categoryservice interface and its implementation class Categoryserviceimpl:


Public interface Categoryservice {public void Save (Category Category);//To test Hibernate environment public void update (Category category); Used to test spring and hibernate consolidation after} public class Categoryserviceimpl implements Categoryservice {@Override//not integrated with spring 
 The condition public void Save (Category Category) {//Gets the session sessions session by the Tool class = Hibernatesessionfactory.getsession (); 
 try {//Manual transaction Session.gettransaction (). Begin (); 
 Execute business logic session.save (category); 
 Manually submit Session.gettransaction (). commit (); 
 The catch (Exception e) {session.gettransaction (). rollback (); 
 throw new RuntimeException (e); 
 finally {hibernatesessionfactory.closesession (); }/*spring and Hibernate after the whole * * Private sessionfactory sessionfactory; Define a sessionfactory//when you need to use sessoinfactory, spring will inject sessionfactory into the public void setsessionfactory ( 
 Sessionfactory sessionfactory) {this.sessionfactory = sessionfactory; Protected session getsession () {//Gets the session from the current thread, and if not, creates a new session 
 return Sessionfactory.getcurrentsession (); 
 @Override//spring and hibernate consolidated situation public void Update (Category Category) {getsession (). Update (Category); 
 } 
}

Now we can add test methods to the test class to test the results of spring and Hibernate integration:

@RunWith (Springjunit4classrunner.class) 
@ContextConfiguration (locations= "Classpath:beans.xml") 
public Class Sshtest { 
 
 @Resource 
 private date date; 
 
 @Resource 
 private Categoryservice categoryservice; 
 
 @Test//test development environment for spring IOC public 
 void Springioc () { 
 System.out.println (date); 
 } 
 
 @Test//test Hibernate development environment, because there is no consolidation, you can direct new public 
 void Hihernate () { 
 Categoryservice categoryservice = new Categoryserviceimpl (); 
 Category Category = new Category ("Men's Leisure", true); 
 Categoryservice.save (category); 
 } 
 
 @Test//test hibernate and Spring consolidation after public 
 void Hibernateandspring () { 
 categoryservice.update (new Category 1, " Leisure women ", true)); Categoryservice through spring from above. 
 } 
 

Then we looked at the database and found that Id=1 's category was modified to be a casual woman, indicating that the update was successful. At this point, spring and Hibernate are integrated successfully.

5. Build the STRUTS2 environment
5.1 Add the appropriate configuration and jar package
         struts2 to run the jar pack I put it in the library of struts2.3.41, directly introduced, no longer repeat. Additionally, configure the Web.xml file as follows:

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /2001/xmlschema-instance "xmlns=" Http://java.sun.com/xml/ns/javaee "xsi:schemalocation=" http://java.sun.com/xml/ Ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id version= "3.0" > <display-name> e_shop</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </ welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apach E.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class> </filter> < Filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern > </filter-mapping> </web-app> 

As above, we have configured a strutsprepareandexecutefilter filter and set the Url-pattern of the filter to *.action, That is, all. The action suffix will first pass through this filter, which is also the entrance to the struts2.
5.2 Creating an action and configuring it in the Struts.xml file
We create an action as follows:

public class Categoryaction extends Actionsupport { 
 private categoryservice categoryservice; The Categoryservice is set up to visually see the different public 
 
 void Setcategoryservice (Categoryservice categoryservice) {Before and after the spring consolidation 
 this.categoryservice = Categoryservice; 
 } 
 
 Public String Update () { 
 System.out.println ("----update----"); 
 System.out.println (Categoryservice); Before and after the integration output different return 
 "index"; 
 
 Public String Save () { 
 System.out.println ("----Save----"); 
 System.out.println (Categoryservice);//before and after integration output different return 
 "index"; 
 } 
 

Then we configure the Struts.xml file, which is placed in the SRC directory:

<?xml version= "1.0" encoding= "UTF-8"?> <! 
DOCTYPE struts public 
 "-//apache Software foundation//dtd struts Configuration 2.3//en" 
 "http:// Struts.apache.org/dtds/struts-2.3.dtd "> 
 
<struts> 
 <package name=" Shop "extends=" Struts-default "> 
 <!--category_update.actiocan: Accessing the Update method--> 
 <action name=" category_* "class= "Cn.it.shop.action.CategoryAction" method= "{1}" > 
 <result name= "index" >/index.jsp</result> 
 </action> 
 </package> 
 
</struts> 

5.3 Test STRUTS2 Environment
The test method is to write a JSP access action, which indicates that the STRUTS2 environment is OK if the action can be created. That is, struts2 a series of processes can be normal walk: jsp-->struts.xml-->action-->struts.xml-->jsp, so that the STRUTS2 environment even if the good. We write a simple index.jsp.

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! 
 
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 
 
 

Then we deploy the following project, open Tomcat Server, enter in the browser: http://localhost:8080/E_shop/index.jsp, can appear normal JSP page, then click Two buttons, still jump to index.jsp, and then we look at the console output information:
----UPDATE----
Null
----Save----
Null

Explain struts2 a line gone, the environment is no problem, so far, struts2 development environment has been completed.
We see that the console outputs null, which means that the categoryservice is empty, that is to say, we didn't get the categoryservice, because we didn't integrate with spring and didn't get injected in, so null is normal. As we go up the information in the console output, we find a message: Choosing bean (Struts) for (com.opensymphony.xwork2.ObjectFactory). In parentheses, struts shows that the action is Struts2 produced before the spring is integrated.

6. Spring and STRUTS2 Integration
6.1 Add the appropriate jar package
Spring and STRUTS2 integration when the jar package is mainly in the spring4.2.4-web inside, including Struts2-spring-plugin-2.3.24.1.jar, guide package no longer repeat.
6.2 Give spring Management the action and its dependencies
Configuring the action and its dependencies in spring's configuration file Beans.xml, we currently have only one action, as shown in the following configuration:

<bean id= "Date" class= "Java.util.Date"/> <bean id= "Categoryaction" 
Cn.it.shop.action.CategoryAction "scope=" prototype "> <property name=" categoryservice "ref=" 
 Categoryservice "/> <!--dependent categoryservice configured Categoryservice--> </bean> with the above and hibernate integration 
 

6.3 Modifying the configuration in Struts.xml
originally in Struts.xml, the class attribute corresponds to the fully qualified name of the action, and now changes the value of the class attribute to the ID value of the Configure action in spring, that is, Categoryaction, as follows:

<struts> 
 <package name= "shop" extends= "Struts-default" > 
 
 <!--class corresponds to the ID value of the action configured in spring Because you want to give Spring admin--> 
 <action name= "category_*" class= "categoryaction" method= "{1}" > 
 <result Name= "index" >/index.jsp</result> 
 </action> 
 </package> 
 
</struts> 

6.4 configuration Listener
        Configure the Listener Contextloaderlistener in Web.xml so that the spring's configuration file can be loaded when the server is started. is as follows:

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "&gt; &lt;display-name&gt;e_shop&lt;/ display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/ welcome-file-list&gt; &lt;filter&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;filter-class&gt;org.apach E.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter&lt;/filter-class&gt; &lt;/filter&gt; &lt; Filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;*.action&lt;/url-pattern &gt; &lt;/filter-mapping&gt; &lt;!--web.xml The listener in the boot priority is higher than the filter, so the following--&gt; &lt;listener&gt; &LT;LISTENER-CLA 
 Ss&gt;org.springframework.web.context.contextloaderlistener&lt;/listener-class&gt; &lt;/listener&gt;
 &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath: 
 Beans.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;

6.5 Test Consolidation Results
We add a new sentence to the action. Update the statement for the database as follows:

public class Categoryaction extends Actionsupport { 
 
 private Category category;//sets a private member variable to receive the parameter that the URL brings over, Note the following to write a get and set method 
 
 private Categoryservice categoryservice; 
 
 public void Setcategoryservice (Categoryservice categoryservice) { 
 this.categoryservice = Categoryservice; 
 } 
 
 Public String Update () { 
 System.out.println ("----update----"); 
 SYSTEM.OUT.PRINTLN (Categoryservice)//Because it is already integrated with spring, so you can get this categoryservice, print out is not null 
 Categoryservice.update (category); Add a new statement to update the database return 
 "index"; 
 
 Public String Save () { 
 System.out.println ("----Save----"); 
 System.out.println (categoryservice); 
 Return "index"; 
 
 Public Category GetCategory () {return 
 Category; 
 } 
 
 public void Setcategory (Category Category) { 
 this.category = Category; 
 } 
} 

Then we modify the index.jsp file as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! 
 
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 

----Update---- 
cn.it.shop.service.impl.categoryserviceimpl@7c5ecf80 
hibernate:update category set hot=? Type=? where id=? 

We see that we can output categoryservice this object, or we can output the SQL statement when executing the UPDATE statement, and then we query the database and find that the type of the id=2 data is updated to gga,hot update to False. As we go up the information that is output from the console, we find a message: Choosing Bean (Spring) for (com.opensymphony.xwork2.ObjectFactory), with spring in parentheses, as compared to the above, Struts2 after integration with spring, the action was given to spring to manage.
At this point, Struts2, Hibernate4 and SPRING4 integration work has been completed, and then can be developed in the SSH environment!

The complete jar package required in SSH consolidation described in this article: Free download

Source of the entire project download address: http://www.jb51.net/article/86099.htm

Original address: http://blog.csdn.net/eson_15/article/details/51277324

(Note: To the end of the project to provide the source code download!) Welcome to our collection or attention)

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.