English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
SSH is not a framework, but a combination of multiple frameworks (Struts+spring+The integration of Hibernate is currently a popular open-source integration framework for Web applications, used to build flexible and easily scalable multi-layer Web applications.
The system integrated with the SSH framework is divided into four layers in terms of responsibility: the presentation layer, the business logic layer, the data persistence layer, and the domain module layer (entity layer).
Struts serves as the overall infrastructure of the system, responsible for the separation of MVC. In the model part of the Struts framework, it controls business jumps and provides support for the persistence layer with the help of the Hibernate framework. On the one hand, Spring acts as a lightweight IoC container, responsible for locating, creating, and managing objects and their dependencies. On the other hand, it enables Struts and Hibernate to work better together.
Use MyEclipse to integrate the three frameworks of SSH and implement a Demo for simulating user registration, corresponding version:
Struts version:2.1;
Spring version:3.1;
Hibernate version:3.3;
1. Preparations before integration
1.Create a Web project as follows:
Note:The package name that supports action must be "action", and the action class must end with Action, that is, in the form of XxxAction, as shown in the figure above
2.Create the database and table:
CREATE DATABASE sshdemo; CREATE table t_user( id INT PRIMARY KEY, username VARCHAR(10), password VARCHAR(20) )
3.Import the database connection pool c3p0jar package, click to download:
c3p0-0.9.2-pre1.jar、mysql-connector-java-5.1.13-bin.jar
2. Configuration of the Struts framework:
1.Select the project, right-click and choose: MyEclipse -> Project Facets[Capabilities] -> Install Apache Struts (2.x) Facet as follows:
2.Select the version, and here I choose2.1Click "Finish" as follows:
3.After completing the above steps, you will find an additional struts.xml file in the src directory, 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> </struts>
4.In WEB-There is an additional configuration code for the struts filter in the web.xml file under the INF directory, as follows:
5.Refer to the figure above and change*.Modify .action to "/*", up to this pointThe configuration of the struts framework is complete;
3. Configuration of the Spring framework:
1. Refer to the configuration of struts, select the project, right-click and choose: MyEclipse -> Project Facets[Capabilities] -> Install Spring Facet, select the version, and choose here3.1As follows:
2.Click "Finish" and you will find a new file in the src directoryapplicationContext.xmlfile, WEB-A spring file has been added to the INF directory-Add form.tld and spring.tld files, and add a piece of code related to the spring configuration to the web.xml file, which means the basic construction of the spring framework is completed (the introduction of namespace will be discussed later), as shown below:
4. Hibernate framework configuration:
1. Refer to the configuration of struts, select the project, right-click and choose: MyEclipse -> Project Facets[Capabilities] -> Install HibernateFacet, select the version, and choose3.3As follows:
2. Click "Finish", and you will find a default package (which can be deleted) has been added to the src directory, and a piece of code has been added to the web.xml file (which will be reconfigured later), as shown below:
3. Support for importing jar packages with the "@Entity" annotation: Select the project, right-click and choose: MyEclipse -> Project Facets[Capabilities] -> Manage... Then follow the steps shown in the figure below:
After completing the above steps, the basic construction of the three major frameworks is completed. Next, we will integrate them.
5. Integration
1In order to make applicationContext.xml look less bulky and for better management, we will store the Hibernate-related configurations in another .xml file and then import it into applicationContext.xml. The specific steps are as follows:
(1Create a file namedhibernateContext.xmlCopy the content of applicationContext.xml to this file, and then make the necessary modifications;
(2The content of the hibernateContext.xml 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 dataSource will be configured in the applicationContext.xml file, and it is referenced here first --> <property name="dataSource" ref="dataSource"></property> !-- Set the Hibernate-related configuration items --> <property name="hibernateProperties"> !-- The props tag is used to inject Properties type properties --> !-- The key must be prefixed with hibernate. --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> !-- The purpose of show_sql is to print SQL statements --> <prop key="hibernate.show_sql">true</prop> !-- Beautify the print format of SQL --> <prop key="hibernate.format_sql">true</prop> !-- a) create-drop: Create the data table when executing the program, and delete the table after execution, which is often used in actual development for testing b) create: Re-create the data table each time the program is executed c) update: When executing the program, it will judge that if it exists, it will not create the table, otherwise it will create the data table, and it will automatically add the fields in the data table according to the properties added in the entity class (in development environment) d) validate: When executing the program, it will judge that if the properties of the entity class are inconsistent with the fields of the table, an error will be reported (in production environment) --> <prop key="hibernate.hbm2ddl.auto">validate</prop> </props> </property> !-- Configure the Hibernate entity class --> <property name="packagesToScan"> !--The list tag is used to inject String[] type properties, whose values are generally the full names of the corresponding bean packages, and the classes in the bean packages are generally corresponding to the tables in the database--> <list> <value>com.beauxie.bean</value> </list> </property> </bean> !-- Configure the hibernateTemplate template --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
(3Remove the configuration of 'sessionFactory' in applicationContext.xml (as it is already configured in hibernateContext.xml), then import the modified hibernateContext.xml content. After importing, the content of applicationContext.xml 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 all are placed in one file, it may appear bulky--> <import resource="hibernateContext.xml"/> </beans>
2On the basis of the original dataSource configuration in the applicationContext.xm file, modify the configuration (database name, username, password, etc.), (Note: the value tag must not contain any spaces or carriage returns!!!),as shown below:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl"> !--If the value attribute is used directly instead of the value tag, the "&" character needs to be escaped (&); if the value tag is used, the <span style="color:#FF0000;">tag must not contain any spaces or carriage returns, as it will convert spaces to " "/span>, resulting in the database connection failing 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="10></property> <property name="minPoolSize" value="2></property> <property name="maxPoolSize" value="10></property> </bean>
3.In applicationContext.xm, configure the spring scanner so that we can automatically load beans by adding spring component annotations to our classes. The specific steps are as follows: (1Configure the context namespace, support context tags, click on the bottom 'Namespaces', and then check the context item:
(2Configure spring scanner:
!-- Configure the spring scanner, and then add spring component annotations to our classes to achieve automatic loading of beans-->
<context:component-scan base-package="com.beauxie.action,com.beauxie.service,com.beauxie.dao">
</context:component-scan>
Up to this point, the setup of the ssh three major frameworks is complete. Next is to implement user registration on the basis of the ssh framework
6. Case: Simple Imitation of User Registration
1.Front-end 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"> <html> <head> <base href="<%=basePath%>"> <title>Welcome to Registration</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> !-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath }/user/regist" method="POST"> !-- You can also use 'user.username' to automatically load the 'user' attribute, but it is not the focus here, so it is manually obtained in the background--> Username: <input type="text" name="username"><br> Password: Code: <input type="password" name="password"><br> <input type="submit" value="Register"> </form> </body> </html>
2.User class code:
package com.beauxie.bean; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author Beauxie * Here, the properties of User should be the same as the fields in the t_user table * Otherwise, you need to manually specify the corresponding field in the table for different properties */ @Entity//Maps the database table @Table(name="t_user")//Without this annotation, the default is the user table public class User { @Id//Corresponds to the primary key in the t_user table private int id;//User ID private String username;//Username 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, operates on the database */ @Repository//This property corresponds to the persistence layer (usually the Dao layer), indicating that it is managed by Spring, and the class name in the corresponding package will also have an "S" public class UserDao { @Autowired//Automatically injected, no need to set it, because it has been configured in the Spring configuration file private HibernateTemplate template; /** * User registration, that is, add a new record to the table * @param user */ public void addUser(User user){ //Add a record to the database in one sentence 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 (usually the Service layer), indicating that it is managed by Spring, and the class name in the corresponding package will also have an "S" public class UserService { @Autowired//It is also automatically injected private UserDao userDao; public void addUser(User user){ //Call the addUser method of the Dao layer userDao.addUser(user); } }
5.UserAction class code:
package com.beauxie.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts;2.ServletActionContext; import org.apache.struts;2.convention.annotation.Action; import org.apache.struts;2.convention.annotation.Namespace; import org.apache.struts;2.convention.annotation.Result; import org.apache.struts;2.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//Used to annotate the control layer component @Namespace("/user")//url prefix @Scope("prototype")//Action is default singleton, but in actual development, it is generally multi-instance, because usually one Action may correspond to multiple different requests //@ParentPackage("struts-default")//Inherit a specific package, the default is “struts-default”, so it can be omitted @Results({ @Result(name="registSuccess",location="/msg.jsp") } public class UserAction { @Autowired//Automatic injection private UserService service ; //Struts defaults to intercepting ".action" and no suffix @Action(value="regist")//Access:/user/regist.action or /user/regist public String regist(){ //Get the request HttpServletRequest request = ServletActionContext.getRequest(); //Retrieve the data submitted by the form String username = request.getParameter("username"); String password = request.getParameter("password"); //Encapsulate userBean User user = new User(); user.setId(1000); user.setUsername(username); user.setPassword(password); //Invoke the method of the service layer to add a record to the database service.addUser(user); //Store the prompt information in the request scope for front-end display request.setAttribute("msg", "Congratulations, you have successfully registered!\nRegistration name: ")}+username); return "registSuccess"; } }
6.Message prompt interface: msg.jsp code is 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"> <html> <head> <base href="<%=basePath%>"> <title>Message Prompt</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> !-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> ${msg } </body> </html>
7.Add the project to the server, start the service, open the browser, and visit: http://localhost/SSHDemo/user/regist
8.Enter username and password, click "Register", and display the result:
9.Console output SQL statements (SQL statements have been configured and beautified in the hibernateContext.xml file):
10.View database results:
This simple case has already ended, and issues such as form data validation and garbled characters were not involved. It should be updated later, right?, ,,,
Summary: Seven, Summary:
1.The integration of the three major frameworks should be done first by introducing each framework and then integrating them;
2.Remember to import the database jar package;
3.The Action class should be placed in a package named "action" and the class name should end with Action, such as "XxxAction";
4.When configuring Hibernate, it is necessary to import the jar package that supports the "@Entity" annotation;
5.You can define the request type intercepted by struts in the struts.xml file, the default is .action and without suffix
6.You can define the filter type of the struts filter in the web.xml file, the default is*.action should be changed to/*;
7.In the applicationContext.xm file, it is necessary to configure the following parts: sessionFactory, Hibernate entity class, HibernateTemplate template, dataSource, Spring scanner (including hibernateContext.xml);
8.It is necessary to add corresponding annotations to each class, as well as annotations on the methods in Action.
Example source code download:http://download.jb51.net/201610/source code/SSHzhuce(jb51.net).rar
That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yanaing Tutorial.
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.