Integrated spring+hibernate based on built STRUTS2 projects in the Eclipse environment

Source: Internet
Author: User

This article is based on the built-in STRUTS2 project integration

Spring+hibernate, if the reader is not familiar with the STRUTS2 project, please read first

Implementation steps:

The first step: introduce the required jar package for spring as shown in:

Second Step: Import hibernate required jar package, as in the jar file selected:

Step three: Import struts-spring integration package, let's call it that.

Fourth step: Import the MySQL driver package:

Fifth step: After all the preparations are in place, create the spring and Hibernate configuration file, named Applicationcontext.xml, as shown in the following configuration:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http:// Www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:context=" http ://www.springframework.org/schema/context "xmlns:task=" Http://www.springframework.org/schema/task "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-3.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/ Spring-task-3.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ SPRING-TX-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd "></BEANS> 

This is the introduction of the Spring configuration file namespace, the specific meaning of the namespace refer to the predecessor information

6.2.3 Spring 2.5 configuration file Details (1)

Sixth step: Configure the Listen for spring in the Web. xml file, as shown in the following configuration:

<?xml version= "1.0" encoding= "UTF-8"? ><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 "> <display-name>sshdemo</        Display-name> <!--Spring Listener configuration Starts--<!--the role of Spring Listener: provide instance (IOC)--<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationcontext.x ml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!--pull the request path to struts filter-<filter> <filter-name>struts2</filter-n Ame> <filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pat Tern>/*</url-pattern> </filter-mapping></web-app>

This is to increase the monitoring of spring on the STRUTS2 project base configuration.

Seventh Step: Build the Business Layer Interface (TESTSERVICEI), implementation class (TESTSERVICEIMPL), and Database Operations layer Interface (TESTDAOI), implementation class (TESTDAOIMPL) under the project

The entire project structure is as follows:

where the DAO layer implementation class we need to inject a session factory (factory injection Please note later in this article), and then open the session factory for the operation of the database, the code is as follows:

 PackageWjt.com.test.dao.impl;Importorg.hibernate.HibernateException;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;ImportWjt.com.test.dao.TestDaoI; Public classTestdaoimplImplementstestdaoi{Privatesessionfactory sessionfactory;  Public voidsetsessionfactory (sessionfactory sessionfactory) { This. Sessionfactory =sessionfactory; }        PrivateSession getcurrentsession () {Try {            returnsessionfactory.getcurrentsession (); } Catch(hibernateexception e) {returnsessionfactory.opensession (); }} @Override Public voidTestdaomethod () {System.out.println ("DAO Layer test Method ..."); if(Getcurrentsession ()! =NULL) {System.out.println ("Session Factory injection success!" "); }            }        }

Where the service layer implementation class we temporarily write an empty method to test the success of the injection of the DAO layer interface object and call the DAO layer method, the code is as follows:

 PackageWjt.com.test.service.impl;ImportWjt.com.test.dao.TestDaoI;ImportWjt.com.test.service.TestServiceI; Public classTestserviceimplImplementstestservicei{PrivateTestdaoi Testdao;  Public voidSettestdao (Testdaoi Testdao) { This. Testdao =Testdao; } @Override Public voidTestservicemethod () {System.out.println ("Service Layer test method ...");    Testdao.testdaomethod (); }}

Where the action layer we inject the service layer interface and call its method on the basis of the original STRUTS2 project, the code is as follows:

 Packagewjt.com.test.action;ImportCom.opensymphony.xwork2.ActionSupport;ImportWjt.com.test.service.TestServiceI; Public classTestactionextendsactionsupport{Privatetestservicei Testservice;  Public voidSettestservice (testservicei testservice) { This. Testservice =Testservice; }     PublicString Execute ()throwsException {System.out.println ("struts==========================");        Testservice.testservicemethod (); return"Success"; }}

The structure layout of the entire S2SH project as shown in the seventh step above, the class used for view mapping is encapsulated under the action package, which we encapsulate under the service package to access the database to manipulate the data, and we encapsulate it under the DAO package.

Eighth step: Configure the Spring+hibernate configuration file

As of now, the preparation of the entire S2SH project is ready, and next we configure Hibernate's data source, session factory, to configure one of spring's cores to control the inversion of the IOC or the dependency injection di.

The configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:task= "Http://www.springframework.org/schema/task" xmlns:tx= "Http://www.springframework.org/schema/tx"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-3.0.xsdhttp//Www.springframework.org/schema/taskhttp//www.springframework.org/schema/task/spring-task-3.1.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop-3.0.xsd> <!--data Source configuration-<bean id= "DataSource"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name= "driverclassname" value= " Com.mysql.jdbc.Driver "/> <property name=" url "value= "jdbc:mysql://localhost:3306/wjt_test?useunicode=true&amp;characterencoding=utf-8&amp; Zerodatetimebehavior=converttonull&amp;autoreconnect=true "/> <property name=" username "value=" root "/&gt        ; <property name= "Password" value= "Wujingtao"/> </bean> <!--configuration Hibernate session Factory--<bean Id= "Sessionfactory"class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" > <property name= "dataSource" ref= "DataSource" /> <property name= "hibernateproperties" > <props> <prop key= "hibernate.h Bm2ddl.auto ">update</prop> <prop key=" Hibernate.dialect ">org.hibernate.dialect.mysql5innodbd ialect</prop> <prop key= "Hibernate.show_sql" >false</prop> <prop key= "Hibernate.format_sql" >true</prop> </props> </property> </bean> <!--injection objects with attribute injection-- <bean id= "Testdao"class= "Wjt.com.test.dao.impl.TestDaoImpl" scope= "prototype" > <property name= "sessionfactory" ref= "Sessionfactory" /><!--refer to the above Hibernate factory--</bean> <bean id= "Testservice"class= "Wjt.com.test.service.impl.TestServiceImpl" scope= "prototype" > <property name= "Testdao" ref= "Testdao"/> </bean> <bean id= "Testaction"class= "Wjt.com.test.action.TestAction" scope= "prototype" > <property name= "testservice" ref= "Testservice"/> & Lt;/bean></beans>

In which the IOC is configured to use the method of attribute injection, we can choose several ways of spring injection according to personal preference, I prefer annotation-based attribute injection method, annotation injection will be given in the subsequent article.

Nineth Step: The Struts2 Runtime object is created by spring, the so-called application IOC

Add the following configuration in the Struts.xml configuration file:

<?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" ><!--here and struts2 version number unified--><struts>    <!--tell Struts2 to use spring to create objects this line of code is new plus-    < Constant Name= "struts.objectfactory" value= "Spring"/>    <packageextends= " Struts-default ">        class=" Wjt.com.test.action.TestAction ">            <result name=" Success "> index.jsp</result>        </action>    </Package ></struts>

Test Project:

Deploy and start a project under Tomcat

Browser address bar Input: Http://localhost:8080/SSHDemo/login

The browser appears as follows:

The eclipse output is displayed as follows: (because we have print information at each level)

Here the complete S2sh project is built and tested.

I was just graduated from the small white, writing the purpose of the article is to do their own notes, blog has unreasonable place also please readers point out!

Integrated spring+hibernate based on built STRUTS2 projects in the Eclipse environment

Related Article

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.