Integrated SSH (Struts, Spring, Hibernate) three frames using MyEclipse (Environment powered + instance source download)

Source: Internet
Author: User
Tags print format tld import database

Objective

SSH is not a framework, but an integration of multiple frameworks (Struts+spring+hibernate), and is now a popular open-source integration framework for Web applications to build flexible, easy-to-scale, multi-tiered Web applications.

The systems that integrate the SSH framework are divided into four tiers: presentation layer, business logic layer, data persistence layer, and Domain module layer (entity layer).

Struts, as the overall infrastructure of the system, is responsible for the separation of MVC, controlling the business jump in the model part of the struts framework, and supporting the persistence layer with the Hibernate framework. Spring, on the one hand, is a lightweight IOC container that is responsible for locating, locating, creating, and managing dependencies between objects and objects, on the other hand, enabling struts and hibernate to work better.


Use MyEclipse to integrate the three major SSH framework, and to achieve a demo user registration, the corresponding version:

Struts version: 2.1;

Spring version: 3.1;

Hibernate version: 3.3;


I. Pre-integration preparation 1. Create a Web project as follows:

Note: The package name that supports action must be "action", and the action class must end with an action, which is the form of xxxaction, as shown in

2. Create a database and a table:

CREATE DATABASE Sshdemo; CREATE table T_user (ID INT PRIMARY key,username varchar), password varchar (20))
3.Import Database Connection pool C3p0jar package, click to download:C3p0-0.9.2-pre1.jar, Mysql-connector-java-5.1.13-bin.jar
Ii. configuration of the Struts framework: 1. Select the item, right-select: MyEclipse, Project Facets[capabilities], Install Apache Struts (2.x) Facet, as follows:

2. Select version, here I choose 2.1, click "Finish", as follows:


3. After completing the above steps, you will find that in the SRC directory, one moreStruts.xmlFile with the following contents:

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

4. In the Web. xml file in the Web-inf directory, there are several configuration codes for the Struts filter, as follows:


5. For reference, change the *.action to "/*", the Struts framework is configured, and the spring Framework is configured:
1. Refer to the configuration of struts, select the project, right-select: MyEclipse, Project Facets[capabilities], Install Spring Facet, select version, choose 3.1 as follows:

2. Click "Finish" to find the SRC directory with one moreApplicationcontext.xmlFile, the Web-inf directory has a spring-form.tld and Spring.tld file, and in the Web. xml file, there is a spring configuration-related code, the spring framework is basically finished (the introduction of namespaces will be discussed later), As shown below:

Iv. configuration of the Hibernate framework:
1. Refer to the configuration of struts, select the project, right-select: MyEclipse, Project Facets[capabilities], Install hibernatefacet, select version, choose 3.3 as follows:


2. Click "Finish", you will find that the SRC directory has a default package (can be deleted), and in the Web. xml file, a section of code (will be reconfigured later), as follows:

3. Support for the "@Entity" annotation of the JAR package import: Select the project, right-select: MyEclipse, Project Facets[capabilities]->manage ..., then follow the steps in the procedure:


By completing the above steps, the three frameworks are basically built up and then integrated.

Five  Integration 1. To keep applicationcontext.xml from looking too bloated and manageable, we'll save hibernate-related configuration in another. xml file, and then import it in Applicationcontext.xml, with the specific steps: (1) in the SRC directory (similar to applicationcontext.xml), create a name ofHibernatecontext.xmlFiles, copy the contents of the Applicationcontext.xml, and then make changes; (2)Hibernatecontext.xmlContents of the 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:p= "http +/ www.springframework.org/schema/p "    xsi:schemalocation=" http://www.springframework.org/schema/ Beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd ">    <!-- Sessionfactory configuration-->    <bean id= "sessionfactory"         class= " Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean ">        <!--The properties of the DataSource are configured in the Applicationcontext.xml file, where they are referenced first-->        < Property Name= "DataSource" ref= "DataSource" ></property>        <!-- Set hibernate-related configuration items-->        <property name= "Hibernateproperties" >    &NBSP;&NBsp;       <!--props tags are intended to inject properties of this type of property-->            <!--key must be added hibernate. prefix-->             <props>                <prop key= " Hibernate.dialect ">org.hibernate.dialect.MySQLDialect</prop>                 <!--show_sql purpose is to print SQL statements-->                 <prop key= "Hibernate.show_sql" >true</prop>                 <!--beautify your SQL print format-->                 <prop key= "Hibernate.format_sql" >true</prop>                 <!--a) Create-drop: Create datasheets when executing programs, delete tables after execution, actually developing, commonly used for testing                      b) Create: Recreate the data table                    Every time the program executes &NBSP;C) Update: When executing the program, it is judged that if there is no table created, the data table is created, and the fields in the data table are automatically incremented based on the increase of the attributes in the Entity class (development environment)                     d) Validate: When executing a program, it is determined that if the attributes in the entity class are inconsistent with the fields in the table, Then error (production environment)-->                <prop key= " Hibernate.hbm2ddl.auto ">validate</prop>            </ props>        </property>        <!-- Configure Hibernate entity classes-->        <property name= "Packagestoscan" >            <!--A list tag is an attribute used to inject string[] type, whose value is generally the full name of the corresponding bean package, The classes in the bean package, in general, correspond to the tables in the database-->            <list>                 <value>com.beauxie.bean</value>            </list>        </property>     </bean>    <!--Configuration hibernatetemplate template-->    <bean id= " Hibernatetemplate "class=" Org.springframework.orm.hibernate3.HibernateTemplate ">         <property name= "sessionfactory" ref= "Sessionfactory" ></property>    </ Bean></beans>
(3) Delete the configuration of "Sessionfactory" in APPLICATIONCONTEXT.XM (because theHibernatecontext.xmlis already configured, and then import the modifiedHibernatecontext.xmlContent, after the import, at this time applicationcontext.xml content 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:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd "> <bean id=" dataSource "class=" Org.apache.commons.dbcp.BasicDataSource "> </b Ean> <!--importing other spring profiles, if placed in a file, will look bloated--<import resource= "Hibernatecontext.xml"/> &L T;/beans>
2. On the basis of the original datasource in the Applicationcontext.xm file, modify its configuration (database name, user name, password, etc.), ( Note: The value tag must not contain spaces, carriage returns!! ), as shown below:
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" ><property name= "Jdbcurl" >< !--If you use the Value property directly, instead of the value tag, you need to escape the "&" (&) with the value tag, <span style= "color: #FF0000;" > tags must not contain spaces, enter, because it will convert the space to "&nbsp;" </span&gt, which causes the database to be disconnected unless the data source is rewritten--><value><! [cdata[jdbc:mysql://localhost:3306/sshdemo?useunicode=true&characterencoding=utf8&useserverprepstmts= true&prepstmtcachesqllimit=256&cacheprepstmts=true&prepstmtcachesize=256& Rewritebatchedstatements=true]]></value></property><property name= "DriverClass" value= " Com.mysql.jdbc.Driver "></property><property name=" user "value=" root "></property>< Property name= "Password" value= "root" ></property><property name= "Acquireincrement" value= "3" ></ Property><property name= "Initialpoolsize" value= "ten" ></property><property name= "MinPoolSize" Value= "2" ></property><property name= "maxpoolsize" value= "Ten" ></property></bean> 
3. In Applicationcontext.xm, the spring scanner is configured so that we can add the spring component annotations to our class to implement the bean's automatic loading, with the following steps: (1) Introduce the context namespace, support the context tag, click on the bottom of the "Namespaces", then tick the context:


(2) Configure the Spring scanner:
<!--Configure the spring scanner, and then add the Spring component annotations to our class to implement the Bean's auto-load--><context:component-scan base-package= " Com.beauxie.action,com.beauxie.service,com.beauxie.dao "></context:component-scan>

At this point SSH three framework environment is set up, next is the SSH framework based on the implementation of user registration


Vi. cases: Simple imitation of user Registration 1. Front Desk Registration page code, INDEX.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

2.User Class Code:
Package Com.beauxie.bean;import Javax.persistence.entity;import Javax.persistence.id;import javax.persistence.table;/** * @author Beauxie * Here the user property should be the same as the field in the T_user table, * otherwise you will need to manually specify the fields in the corresponding table for the different properties */@Entity// Map database table @table (name= "T_user")//Do not add this annotation, the default corresponding to the user table public class User {@Id//corresponding T_user table of the primary key private int id;//user idprivate String username;//user name private String password;//password public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}
3.UserDao Class Code:
Package Com.beauxie.dao;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.orm.hibernate3.hibernatetemplate;import Org.springframework.stereotype.repository;import com.beauxie.bean.user;/** * @author Beauxie * DAO layer, operate the database */@Repository//This property corresponds to the persistence layer (usually the DAO layer), the description is given to spring management, The class name under the corresponding package will also have an "S" public class Userdao {@Autowired//auto-injection, no need to set a value because the private hibernatetemplate template is already configured in the Spring configuration file /** * User registration, adding a new record to the table * @param user */public void AddUser (user user) {//Add a piece of data to the database, a word can be done template.save (user);}}
4.UserService Class Code:
Package Com.beauxie.service;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.beauxie.bean.user;import com.beauxie.dao.userdao;/** * @author Beauxie * Service Layer */@Service//This property corresponds to the business layer is generally service layer), the description is given to spring management, and the corresponding package under the class name will also have a "S" public class UserService {@ autowired//is also automatically injected with private Userdao userdao;public void addUser (user user) {//Call the DAO Layer AddUser method Userdao.adduser (user);}}
5.UserAction Class Code:
Package Com.beauxie.action;import Javax.servlet.http.httpservletrequest;import Org.apache.struts2.servletactioncontext;import Org.apache.struts2.convention.annotation.action;import Org.apache.struts2.convention.annotation.namespace;import Org.apache.struts2.convention.annotation.Result; Import Org.apache.struts2.convention.annotation.results;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Scope; Import Org.springframework.stereotype.controller;import Com.beauxie.bean.user;import com.beauxie.service.userservice;/** * @author Beauxie * */@Controller//For labeling Control layer Components @namespace ("/user")//url prefix @scope (" Prototype ")//action is a singleton by default, but in practice, it is generally a multi-instance, because generally an action may correspond to several different requests//@ParentPackage (" Struts-default ")//Inherit specific package , the default is "Struts-default", so you can omit the Do not write @results ({@Result (name= "registsuccess", location= "/msg.jsp")}) public class useraction {@Autowired//automatic injection of private userservice service,//struts default interception ". Action and no suffix" @Action (value= "regist")//Access: /user/regist.actiOn or/user/registpublic String regist () {//GET request HttpServletRequest request = Servletactioncontext.getrequest ();  Gets the data submitted by the form String username = request.getparameter ("username");  String Password = request.getparameter ("password");  Package Userbean User user = new user ();  User.setid (1000);  User.setusername (username);    User.setpassword (password);    Call the service layer method to add a record service.adduser (user) to the database; Save the prompt to the request field for the foreground display Request.setattribute ("MSG", "Congratulations, registration is successful!")  <br> registered Name: "+username"); return "Registsuccess";}}
6. Message Prompt Interface: msg.jsp code, as follows:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%>&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
7. Add the project to the server, start the service, open the browser, visit: http://localhost/SSHDemo/user/regist

8. Enter your username and password and click "Register" to display the results:

9. The console output SQL statement (in Hibernatecontext.xmlThe file has already been configured with output and beautify the SQL statement):

10. View Database Results:

This simple case is over, the data validation of the form submission, as well as the garbled problem is not involved, the follow-up should be updated 、、、


Vii. Summary:

1. The integration of the three frameworks should be preceded by the introduction of each framework and re-integration;

2. Always remember to import the database jar package;

The 3.Action class should be placed under a package named "Action", and the class name should end with action, as in the form "xxxaction";

4. When configuring Hibernate, be sure to import a jar package that supports "@Entity" annotations;

5. The request type for struts interception can be defined in the Struts.xml file, with the default. Action and no suffix

6. The filter type of the struts filter can be defined in the Web. xml file, which defaults to *.action and should be changed to/*;

7. In the Applicationcontext.xm file you need to configure: Sessionfactory, Hibernate entity class, hibernatetemplate template, Data source DataSource, Spring Scanner five part (contains hibernatecontext.xml) ;

8. Be sure to add the corresponding annotations to each class, and also annotate the methods in the action.


Example Source download: http://download.csdn.net/detail/beauxie/9665583


Integrated SSH (Struts, Spring, Hibernate) three frames using MyEclipse (Environment powered + instance source download)

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.