Java S2SH Project Framework Integration Building Example Tutorial

Source: Internet
Author: User

Original:Java S2SH Project Framework Integration Building Example Tutorial

Source code: Http://www.zuidaima.com/share/1787220771113984.htm


Now the development of a project using the S2SH framework, configuration of the environment for a day or two, now the configuration of the environment when the document was written out, but also to strengthen the point of memory.

1 development environment

? MyEclipse5.5

? JDK 1.6

? Java EE 5.0

? Tomcat6.0

? Struts2.1.6

? Spring2.5.6

? Hibernate3.3.1

2 Getting ready for SSH

2.1 Download Package

? Struts2.1.6 Package Download:

http://struts.apache.org/download.cgi#struts216

    • Full distribution:
      • Struts-2.1.6-all.zip (110MB) [PGP] [MD5]

? Hibernate3.3 Package Download:

Https://www.hibernate.org/6.html

? Spring2.5 Download:

Http://www.springsource.org/download

2.2 Building the development environment

Open MyEclipse, create a new Web project,

Note: The EE version is set to Java EE 5.0


Click Finish to build the project

If your myeclipse has not yet configured a Web server, take the following steps, as an example of TOMCAT6:

Open the Myeclipseàpreferences window and expand the directory tree as follows:

Set your Tomcat6 path, if you want to install Tomcat first. There is also a point to note that you see the directory tree tomcat6.x the following JDK? Click on it and make the Tomcat JDK jdk1.6 to match the MyEclipse.

Well, the project has been built, so let's start configuring struts. Download the struts package before the configuration, and the above is given.

3 Configuring Struts2.0

3.1 Basic Configuration

1) introduce five jar packages required by struts. After downloading Struts-2.1.6-all.zip decompression, the Struts-2.1.6\lib directory is the relevant jar package for struts. So many jar packages are not struts must be, using struts only need to put the following five to introduce, and later to use what jar package, and then introduced.

? 2; Commons-logging-1.0.4.jar

? 2; Freemarker-2.3.13.jar

? 2; Ognl-2.6.11.jar

? 2; Struts2-core-2.1.6.jar

? 2; Xwork-2.1.2.jar

2) Modify the Web. xml file under Web-inf to increase the struts2 configuration. Add the code as follows: These configuration codes are immutable for struts2 and are copied directly to Web. Xml.

<filter>  <filter-name> struts2 </filter-name>  <filter-class>  Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class>  </filter>  <filter-mapping>  <filter-name> struts2 </filter-name>  <url-pattern>/* </ Url-pattern>  

3) Add a struts configuration file. In the Web-inf/classes directory, create a new struts.xml with the following template:

<?xml version= "1.0" encoding= "UTF-8"?> <!  DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/dtds/ Struts-2.0.dtd ">  <struts>  

OK, struts basic configuration is complete, is not very simple?

Now publish the project to Tomcat to test, right-click on the project name, select Myeclipseàadd and Remove project deployments, in the Open window, click Add, select our previously configured TOMCAT6 server, Such as:

Release OK, start Tomcat, if no exception is started, the configuration is successful.

Note: Struts-default.xml related exceptions may occur and the associated jar packages are introduced as prompted. When I was testing, I was missing the FileUpload related jar package, so I introduced the commons-fileupload-1.2.1. jar.

3.2 Configuring an action

Let's start by configuring an action, as an example of user login:

1) First create a new landing page login.jsp, the code is as follows:

<% @ Page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% @ taglib prefix= "s" uri= "/struts-tags" %>  <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

2) Configure the login action in the struts.xml that we have built. The name of the login action defined here is login and the configuration code is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!  DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/dtds/ Struts-2.0.dtd ">  <struts>  <package name=" struts2 "extends=" Struts-default "> <action name = "Login" class= "test". Loginaction "> <result name=" Success "type=" redirect ">index.jsp </result>  <result name=" Input " >login.jsp </result>  <result name= "error" > login.jsp </result>  </action>  </package>  

3) write the specific action class below. The code is as follows:

Package Test;import Com.opensymphony.xwork2.actionsupport;public Class Loginaction extends Actionsupport {public String Username;public string Password;public string Execute () {if (!username.equals ("admin")) {Super.addfielderror (" Username "," user name is wrong! "); return ERROR;} if (!password.equals ("001")) {super.addfielderror ("password", "Password wrong!") "); return ERROR;} return SUCCESS;} public void Validate () {if (username = = NULL | | username.length () = = 0) {super.addactionerror ("User name cannot be empty");} if (password = = NULL | | password.length () = = 0) {super.addactionerror ("Password cannot be empty");}}}

4) OK, one action is created, restart the Tomcat test. If you use struts for the first time, you may understand the above code, and then you can learn it later, so let's take a look at the effect.

Open the login page http://localhost:8080/test/login.jsp, enter the correct or incorrect user name and password to see what the hint is.

4 Configuring Hibernate

4.1 Basic Configuration

1) Import the smallest jar package, which is the jar package necessary to use Hibernate3. After downloading Hibernate-distribution-3.3.1.ga decompression, the required jar packages are in the Lib "required directory. The required jar packages are as follows:

? 2; Hibernate3.jar-----------------------------Core Class Library

? 2; Antlr-2.7.6.jar-----------------------------code scanner for translating HQL statements

? 2; One of the Commons-collections-3.1.jar-----------Apache Commons packages contains a collection class developed by Apache that is more powerful than java.util.*

? 2; Dom4j-1.6.1.jar----------------------------is a Java XML API, similar to Jdom, used to read and write XML files.

? 2; Javassist-3.4.ga.jar-----------------------javassist byte-code interpreter

? 2; Jta-1.1.jar------------------------------------the standard JTA API.

? 2; Slf4j-api-1.5.2.jar

? 2; Slf4j-nop-1.5.2.jar

1) Create Hibernate configuration file. Create a new hibernate.cfg.xml under the Web-inf "Calsses directory (under Project SRC package). This is the configuration file for Hibernate connection database. Here's an example of connecting to Oracle:

<?xml version= ' 1.0 ' encoding= ' UTF-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd "> 

1) Create session factory class Hibernatesessionfactory.

Let us first understand the session, Hibernat to the database operation is achieved through the session, the session here is different from the page passed the parameters of the session, but similar to the Connection in JDBC. Session is the center of Hibernate operation, object life cycle, transaction management, database access are closely related to the session.

The session is created by Hibernatesessionfactory, which is thread-safe and allows multiple threads of execution to access hibernatesessionfactory at the same time without the problem of data sharing. But you cannot have multiple threads sharing a session.

Hibernatesessionfactory can be created automatically with Myeclispe, and the code is not posted here.

Note: Don't forget to bring the database driver package into the project. For Oracle is Class12.jar.

4.2 Example

Go and test it yourself.

5 Configuring Spring2.5

5.1 Basic Configuration

1) Import the spring package. After downloading the spring-framework-2.5.6 and extracting it, find Spring.jar in the spring-framework-2.5.6 "Dist directory and bring it into the project.

Description: Spring.jar is a single jar package that contains a full release, and the Spring.jar contains all but The contents of all the other jar packages contained in the Spring-mock.jar, because only in the development environment will use the Spring-mock.jar to carry out the auxiliary testing, the formal application system is not used in these classes. In addition to the Spring.jar file, Spring includes 13 other separate jar packages, each containing a corresponding spring component, which allows the user to choose to assemble their own jar packages, rather than having to introduce all of the Spring.jar's class files. Here, for ease of use, we introduce the entire spring.jar.

2) Configure the Web. xml file. After the introduction of the jar package, we begin to configure spring, first modify the Web. xml file and add the following code:

<!--* Load the spring configuration file from the Classpath, multiple profiles can be separated by commas and spaces * classpath: Keywords specified in the class path load-up  <context-param>  < param-name> contextconfiglocation </param-name>  <param-value>  classpath*:spring/ Applicationcontext*.xml </param-value>  

Here, we specify the path to the spring configuration file, which is the XML file named ApplicationContext at the beginning of the web-inf/classes/spring directory.

3) Create a new applicationcontext.xml file below src. First, add the spring header to this file:

<?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:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-2.5.xsd ">  

Note: The header is 2.5 do not introduce 2.0, wrong may spring will not load correctly.

5.2 Example

Spring basic configuration is complete, let's build an example to test it, first create two Java files under the test.spring package: Tuser.java, Springtest.java.

Tuser.java:

Package Test.spring;public class TUser implements java.io.Serializable {private string username;private string allname; private string Address;public string GetUserName () {return this.username;} public void Setusername (String username) {this.username = username;} Public String Getallname () {return this.allname;} public void Setallname (String allname) {this.allname = Allname;} Public String getaddress () {return this.address;} public void setaddress (String address) {this.address = address;}}

Springtest.java:

Package Test.spring;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Springtest {public static void main ( String[] (args) {//Load Spring config file, initialize IOC container applicationcontext ac = new Classpathxmlapplicationcontext ("spring/ Applicationcontext.xml ");//take over beantuser user = (TUser) ac.getbean (" TUser ") from the container;//Output Welcome message System.out.println (" Hello: "+ User.getusername () + "; u are in" + user.getaddress () + "; and U is  "+ user.getallname ());}}

Once created, the last step remains, configure a bean in Applicationcontext.xml and add the following code to the XML:

<bean id= "TUser" class= "Test.spring.TUser" > <property name= "username" value= "Xiao Zhang" ></property> < Property Name= "Allname" value= "Zhang San" ></property> <property name= "Address" value= "Qingdao" ></property >  

OK, let's run it down, right-click Springtest.java Select Run Asàjava application, and the results are as follows:


If you run the same result as above, and there is no exception, the spring configuration is successful. Isn't it simple? Don't be proud, it's important to integrate spring with hibernate and struts. Go ahead!

5.3 Integrated Struts

The integration of spring and struts is actually to give the struts action class to spring to manage, let's start!

1) Import the jar package. Find the Struts2-spring-plugin-2.1.6.jar in the Struts2.1.6 Lib directory and bring it into the project.

2) Configure the Web. xml file. Add the following code to Web. XML:

<listener>  <listener-class>  org.springframework.web.context.ContextLoaderListener </ Listener-class>  

1) Now let's see how the struts action is given to spring. As an example of login.action in the struts example, first create a bean of the Loginaction class. Add the following code to the Applicationcontext.xml:

<bean id= "loginaction" class= "Test.action.LoginAction" scope= "prototype" >

</bean>

Here, we set this bean's ID to loginaction. Scope is set to prototype, meaning that each request creates an instance of the Loginaction class, and the scope has another value of "singleton" meaning "singleton mode".

Next modify the Struts.xml file, the original login.action configuration to make the following changes:

Put <action name= "login" class= "Test.action.LoginAction" >

Switch

<action name= "Login" class= "Loginaction" >

Notice what the difference is? The class value is set to Loginaction, which is the ID of the bean of the Loginaction class. So we gave the Loginaction class to spring management. As for the specific how to deal with the secret in the Struts2-spring-plugin-2.1.6.jar, have time to study it, now it will be used.

5.4 Integration Hibernate

Spring integration Hibernate mainly manages the session of Hibernate, including the entire lifecycle of session creation, submission, and closure. Spring applies AOP techniques to the management of transactions, before configuring the knowledge of AOP.

1) Configure the sessionfactory and let spring create the session. Add the following code to the Applicationcontext.xml:

<!--configuration Sessionfactory--  <bean id= "sessionfactory" class= " Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <property name=" configlocation ">  < value> classpath:spring/hibernate.cfg.xml </value>  </property>  

We used to create the session with Hibernatesessionfactory.java, now delete it and give it to spring to create. Here, a bean with the session factory class is created with the id "sessionfactory".

2) Configure the transaction manager. Add the following code:

<!--configuration transaction Manager-  <bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name=" sessionfactory "> < Ref bean= "Sessionfactory"/>  </property>  

This creates a transaction manager with ID TransactionManager, which matches a session factory, <ref bean= "Sessionfactory"/> This sessionfactory refers to the ID of the session factory.

3) transaction settings for the transaction manager. Add the following code:

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

A advice (notification) is created here, and the transaction manager is set up for transaction, meaning that the transaction is applied to the method beginning with Save, Del, and update.

4) Apply the transaction to the specific class below. Look at the following code:

<aop:config> <aop:pointcut id= "Smmethod" expression= "Execution (*test.service.impl.*.* (..))"/>  <aop:advisor pointcut-ref= "Smmethod" advice-ref= "Smadvice"/>  

The purpose of this configuration is to apply the advice we have created above to a specific class. The above code means to apply Smadvice to all methods of all classes under Test.service.impl.

5) Example: Use session.

Configuration basically finished, to test it yourself, here will not write first.

Java S2SH Project Framework Integration Building Example Tutorial

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.