MyEclipse Integrated SSH Three framework environment with user registered source download _java

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

Objective

SSH is not a framework, but an integration of multiple frameworks (Struts+spring+hibernate), a more popular web application open Source Integration Framework for building flexible, scalable, multi-tier Web applications.

The system of integrated SSH framework is divided into four layers: presentation layer, business logic layer, data persistence layer and Domain module layer (entity layer).

Struts as the overall infrastructure of the system, responsible for the separation of MVC, in the struts framework of the Model section, control business jumps, using the Hibernate framework to support the persistence layer. As a lightweight IOC container, spring is responsible for finding, locating, creating, and managing dependencies between objects and objects, and on the other, enabling struts and hibernate to work better.

Use MyEclipse to consolidate the three major SSH frameworks and implement a demo with user registration, corresponding version:

Struts version: 2.1;

Spring version: 3.1;

Hibernate version: 3.3;

I. Preparatory work before integration

1. Create a Web project, as follows:

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

2. Create DATABASE and table:

CREATE DATABASE Sshdemo; 
CREATE table T_user ( 
ID INT PRIMARY KEY, 
username VARCHAR (), 
password VARCHAR 
) 

3. Import Database connection pool C3p0jar package, click to download:

C3p0-0.9.2-pre1.jar, Mysql-connector-java-5.1.13-bin.jar

Second, the Struts framework configuration:

1. Select the item, right click:myeclipse-> Project Facets[capabilities]-> Install Apache Struts (2.x) Facet, as follows:

2. Select the version, where I selected is 2.1, click "Finish", as follows:

3. After completing the above steps, you will find a struts.xml file under the SRC directory, which reads as follows:

<?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> 
 

4. In the Web.xml file under the Web-inf directory, there are a few more configuration codes for struts filters, as follows:

5. Refer to the above figure, the *.action modified to "/*", the Struts framework configuration completed;

Iii. configuration of the Spring framework:
1. Refer to Struts configuration, select item, right click: MyEclipse-> Project Facets[capabilities]-> Install Spring Facet, select version, this choice 3.1 is as follows:

2. Click "Finish", you will find the SRC directory more than a applicationcontext.xml file, There is a spring-form.tld and Spring.tld file in the Web-inf directory, and a section of the Web.xml file that has something to do with the spring configuration, the spring framework is almost finished (the introduction of namespaces is described later), as follows:

Iv. configuration of the Hibernate framework:

1. Refer to Struts configuration, select items, right-click Select: MyEclipse-> project Facets[capabilities]-> Install hibernatefacet, select version, select 3.3 below:

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

3. jar package imports that support the "@Entity" annotation: Select the item, right-click to select: MyEclipse-> project Facets[capabilities]->manage ..., and then follow the steps in the following figure:

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

V. Integration

1. In order not to make the applicationcontext.xml look too bloated and easy to manage, we save the hibernate-related configuration in another. xml file, and then import it in Applicationcontext.xml, which is specific steps:

(1) Create a file named hibernatecontext.xml in the src directory (with applicationcontext.xml siblings), Copy the contents of the Applicationcontext.xml, and then make changes;

(2) The contents of the Hibernatecontext.xml file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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.springframewo Rk.orm.hibernate3.annotation.AnnotationSessionFactoryBean "> <!-- The DataSource properties are configured in the Applicationcontext.xml file, where the--> <property name= "DataSource" ref= "DataSource" is referenced first ></ Property> <!--set Hibernate related configuration items--> <property name= "Hibernateproperties" > <!--props tags are to inject prope Rties This type of attribute--> <!--key must be added hibernate. prefix--> <props> <prop key= "Hibernate.dialect" >org.hibe Rnate.dialect.mysqldialect</prop> <!--Show_sql The purpose is to print SQL statements--> <prop key= "Hibernate.show_sql" >true</prop> <!--print format to beautify SQL--> <prop key= "Hibernate.format_sql" >true</prop> <!--a) CRE Ate-drop: Create a data table when executing a program, delete the table after execution, in actual development, often used to test B create: Recreate the data table at each execution of the program C) Update: When executing a program, it is judged that if it exists, no table is created, or the data table is created, and automatically increases the fields in the datasheet (development environment) d) based on an increase in the attributes in the entity class (validate): When executing a program, it is judged that if the attributes in the entity class are inconsistent with the fields in the table, the error (production environment)--> <prop key= "Hibe Rnate.hbm2ddl.auto ">validate</prop> </props> </property> <!--Configure Hibernate entity classes--> &L The T;property name= "Packagestoscan" > <!--list label is used to inject the properties of the string[type, whose value is generally the full name of the corresponding bean package, and the class in the bean package typically corresponds to the table in the database- 
 
 > <list> <value>com.beauxie.bean</value> </list> </property> </bean> <!--Configure hibernatetemplate templates--> <bean id= "Hibernatetemplate" class= Rnatetemplate "> <property name=" sessionfactory "ref=" sessionfactory "></property> </bean> </ Beans>

(3) Delete "Sessionfactory" in APPLICATIONCONTEXT.XM Configuration (because it is already configured in the Hibernatecontext.xml), and then import the Hibernatecontext.xml content that has been modified, and then after the import, the Applicationcontext.xml content 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: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 "> 
 </bean> 
 
 <!--Import other spring configuration files, if they are all in one file, It's going to look bloated 
 .--> <import resource= "Hibernatecontext.xml"/> 
 

2. On the basis of the original datasource in the Applicationcontext.xm file, modify its configuration (database name, username, password, etc.), ( Note: The value tag must not contain spaces, enter!!) ), as follows:

<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 & (&), with the value tag, <span style= "color: #FF0000;" > label must not contain spaces, enter, because it will convert the space to " " &LT;/SPAN&GT, causing the database will not be connected, unless the data source rewrite--> <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> &LT;property name= "Maxpoolsize" value= "ten" ></property> </bean> 

 

3. In Applicationcontext.xm, the spring scanner is configured so that we can add the Spring component annotation to our class to implement the bean's automatic loading, as follows: (1) The introduction of the context namespace, support for the scope tag, click on the bottom of the "Namespaces", then check the context of the item can be:


(2) Configure the Spring scanner:

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

To this end, the three SSH framework environment is completed, followed by the SSH framework based on the implementation of user registration

Vi. case: Simple imitation of user registration

1. Front 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 + "/" 
; %> <! 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's properties should be the same as the fields 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")/Without this annotation, the default corresponds to the user table public 
class User { 
 
 @Id//corresponding primary key 
 in the T_user table private int id;//User ID 
 
 private string username;//user name 
 
 private string password;//password public 
 
 
 int getId () C17/>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//The property corresponds to the persistence layer (typically the DAO layer), which is given to spring management, The class name under the corresponding package will also have an "S" public 
class Userdao { 
 
 @Autowired//automatic injection without setting a value because private is already configured in the Spring configuration file 
 Hibernatetemplate template; 
 
 
 /** 
 * User registration, that is, add 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 the service layer), instructions to spring management, and the corresponding package under the class name will also have a The "S" public 
class UserService { 
 
 @Autowired//is also automatically injected into 
 private Userdao Userdao; 
 
 public void AddUser (user user) { 
 //Call AddUser method 
 Userdao.adduser (user) for DAO layer; 
 } 
 

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 marking the control layer component @Namespace ("/user")//url prefix @Scope ("prototype")//action default is a single example, but the actual In development, more often than not, because a general action may correspond to several different requests//@ParentPackage ("Struts-default")//inherit a specific package, the default is "Struts-default", Therefore, you can omit @Results not written ({@Result (name= "registsuccess", location= "/msg.jsp")}) public class Useraction {@Autowired//automatic 
 
 Inject private userservice service; StrUTS the default intercept ". Action and no suffix" @Action (value= "regist")/access:/user/regist.action or/user/regist public String regist () {/ 
  
 /GET request HttpServletRequest request = Servletactioncontext.getrequest (); 
 Get data for form submission String username = request.getparameter ("username"); 
 String Password = request.getparameter ("password"); 
 Encapsulation Userbean User user = new user (); 
 User.setid (1000); 
 User.setusername (username); 
 
 User.setpassword (password); 
 
 Call the service layer method to add a record to the database Service.adduser (user); The prompt is stored in the request field for the foreground display Request.setattribute ("MSG", "Congratulations, registration success!") 
 
 <br> Registration 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 + " /"; 
%> 
 
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 
 
 

7. Add the project to the server, start the service, open the browser, access: http://localhost/SSHDemo/user/regist

8. Enter username and password, click "Register", display the result:

9. Console output SQL statement (the output is already configured in the Hibernatecontext.xml file and the SQL statement is beautified):

10. View Database Results:

This simple case has been completed, about the form submission data validation, and garbled problem is not involved, the follow-up should be updated 、、、

Vii. Summary:

1. The integration of the three major frameworks should be preceded by the introduction of each framework and then integrated;

2. Be sure to 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 an action, shaped like "xxxaction";

4. When configuring Hibernate, be sure to import jar packages that support "@Entity" annotations;

5. You can struts.xml the request type in the file to define struts interception by default. Action and no suffix

6. You can web.xml the file to define the filter type of struts filter, default to *.action, should be changed to/*;

7. Configuration is required in the Applicationcontext.xm file: Sessionfactory, Hibernate entity classes, hibernatetemplate templates, data source DataSource, Spring scanner five parts ( Contains hibernatecontext.xml);

8. Each class must be accompanied by a corresponding annotation, as well as in the action of the method also need to add annotations.

Instance source download: Http://xiazai.jb51.net/201610/yuanma/SSHzhuce (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, 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.