Preface
SSH is not a framework, but an integration of multiple frameworks (struts+spring+hibernate). It is currently a popular open source integration framework for web applications, used to build flexible and easy-to-scaling multi-layer web applications.
The system integrating the SSH framework is divided into four layers in terms of responsibility: presentation layer, business logic layer, data persistence layer and domain module layer (entity layer).
As the overall infrastructure of the system, Struts is responsible for the separation of MVC. In the model part of the Struts framework, it controls business jumps and uses the Hibernate framework to provide support for the persistence layer. On the one hand, Spring is a lightweight IoC container, responsible for finding, positioning, creating and managing dependencies between objects and objects, and on the other hand, it can make Struts and Hibernate work better.
Use MyEclipse to integrate the three major SSH frameworks and implement a demo that simulates user registration, corresponding to the version:
Struts version: 2.1;
Spring version: 3.1;
Hibernate version: 3.3;
1. Preparation 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, the form is like XxxAction, as shown in the above figure
2. Create a 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 Struts framework:
1. Select the project and right-click to select: MyEclipse -> Project Facets[Capabilities] -> Install Apache Struts (2.x) Facet, as follows:
2. Select the version, here I chose 2.1, click "Finish", as follows:
3. After completing the above steps, you will find that there is an extra struts.xml file in the src directory, 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 is an additional section of configuration code for struts filters, as follows:
5. Refer to the above figure, modify *.action to "/*", and the struts framework is configured at this point;
3. Spring framework configuration:
1. Refer to the configuration of struts, select the project, right-click and select: MyEclipse -> Project Facets[Capabilities] -> Install Spring Facet, select the version, and select 3.1 as follows:
2. Click "Finish" and you will find that there is an applicationContext.xml file in the src directory, an spring-form.tld and spring.tld files in the WEB-INF directory, and a piece of code related to spring configuration is added in the web.xml file. The construction of the spring framework has been basically completed (the introduction of the namespace will be discussed later), as shown below:
4. Configuration of Hibernate framework:
1. Refer to the configuration of struts, select the project, right-click and select: MyEclipse -> Project Facets[Capabilities] -> Install HibernateFacet, select the version, and select 3.3 here as follows:
2. Click "Finish" and you will find that there is an additional default package in the src directory (can be deleted) and a piece of code in the web.xml file (it will be reconfigured later), as shown below:
3. Import jar packages that support the "@Entity" annotation: select the project, right-click to select: MyEclipse -> Project Facets[Capabilities] ->Manage..., and then follow the steps in the following figure:
After completing the above steps, the three major frameworks are basically built, and then they are integrated.
5. Integration
1. In order to prevent applicationContext.xml from looking too bloated and easy to manage, we save the Hibernate-related configuration in another .xml file, and then import it in applicationContext.xml. The specific steps:
(1) Create a file named hibernateContext.xml in the src directory (same level as applicationContext.xml), copy the contents in applicationContext.xml, and then make changes;
(2) Contents in 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" > <!-- The dataSource property will be configured in the applicationContext.xml file. Ref="dataSource"></property> <!-- Set hibernate-related configuration items --> <property name="hibernateProperties"> <!-- Props tag is to inject properties of Properties type --> <!-- The key must be hibernate.prefix--> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- show_sql is the purpose of printing sql statements --> <prop key="hibernate.show_sql">true</prop> <!-- Beautify the printing format of SQL --> <prop key="hibernate.format_sql">true</prop> <!-- a) create-drop: Create a data table when executing the program, and delete the table after execution. In actual development, it is often used for testing b) create: Recreate the data table every time the program is executed c) update: When executing the program, it will be judged that if there is, the table will not be created, otherwise the data table will be created, and the fields in the data table will be automatically added according to the increase of attributes in the entity class (development environment) d) validate: When executing the program, if the attributes in the entity class are inconsistent with the fields in the table, an error will be reported (production environment) --> <prop key="hibernate.hbm2ddl.auto">validate</prop> </props> </property> <!-- Configure the entity class of hibernate --> <property name="packagesToScan"> <!-- List tag is used to inject the property of the String[] type. Its value is generally the full name of the corresponding bean package, and the classes in the bean package generally correspond to the table in the database --> <list> <value>com.beauxie.bean</value> </list> </property> </bean> <!-- Configure the hibernateTemplate template--> <bean id="hibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
(3) Delete the configuration of "sessionFactory" in applicationContext.xm (because it has been configured in hibernateContext.xml), and 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" > </bean> <!-- Import other spring configuration files. If they are placed in one file, they will look bloated --> <import resource="hibernateContext.xml"/> </beans>
2. Based on 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 or enter!! ), as shown below:
<bean id="dataSource"> <property name="jdbcUrl"> <!--If you use the value attribute directly instead of the value tag, you need to escape "&" and use the value tag. The <span style="color:#FF0000;"> tag must not contain spaces or carriage return, because it will convert the spaces into ""</span>, resulting in the database being unable to connect 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 as to add spring component annotations to our class, and the bean can be automatically loaded. The specific steps are as follows: (1) Introduce the context namespace, support the context tag, click "Namespaces" at the bottom, and then check the context item:
(2) Configure the spring scanner:
<!-- Configure spring scanner and add spring component annotations to our class to automatically load beans -->
<context:component-scan base-package="com.beauxie.action,com.beauxie.service,com.beauxie.dao">
</context:component-scan>
At this point, the three major ssh framework environments have been built, and the next step is to implement user registration based on the ssh framework.
6. Case: 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 + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Welcome to register</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 point here, so you can manually get its value in the background--> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="registration"> </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 the User should be the same as the fields in the t_user table, * Otherwise, you need to manually specify the fields in the corresponding table for different properties*/ @Entity//Map database table @Table(name="t_user")//Not adding this annotation, the default corresponding to the user table public class User { @Id//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, operate on the database*/ @Repository//This property corresponds to the persistence layer (usually Dao layer), which means it is handed over to spring management, and the corresponding class name under the package will also have a "S" public class UserDao { @Autowired//Autowired, no need to set values, because private HibernateTemplate template has been configured in the spring configuration file; /** * User registration, that is, add a new record to the table* @param user */ public void addUser(User user){ //Add a data into the database, and you can get 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 service layer generally is the Service layer), which means that it is handed over to spring management, and the corresponding class name will also have a "S" public class UserService { @Autowired//Also it will automatically inject private UserDao userDao; public void addUser(User user){ //Calling the addUser method of Dao layer 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.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 a singleton by default, but in actual development, it is generally multiple cases, because generally one Action may correspond to multiple different requests //@ParentPackage("struts-default")//Inherit a specific package, the default is "struts-default", so @Results({ @Result(name="registSuccess",location="/msg.jsp") }) public class UserAction { @Autowired//Automatically inject private UserService service; //Struts defaults to intercept ".action and without any suffix" @Action(value="regist")//Access: /user/regist.action or /user/regist public String regist(){ //Get request HttpServletRequest request = ServletActionContext.getRequest(); //Get form submitted data 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); //Call the service layer method to add a record to the database service.addUser(user); //Save the prompt information into the request domain and display request.setAttribute("msg", "Congratulations, registration is successful! <br>Register 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"> <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 the user name and password, click "Register" to display the results:
9. The console outputs the SQL statement (the output has been configured and the SQL statement has been beautified in the hibernateContext.xml file):
10. View database results:
This simple case has ended. There is no problem with the form submission data verification and garbled code. It should be updated in the future.
7. Summary:
1. The integration of the three major frameworks should be introduced first and then integrated;
2. Be sure to remember to import the database jar package;
3. The Action class should be placed under the package name "action", and the class name should end with Action, like "XxxAction";
4. When configuring Hibernate, be sure to import jar packages that support the "@Entity" annotation;
5. You can define the request type for struts intercepted in the struts.xml file, which defaults to .action and without suffixes.
6. You can define the filter type of the struts filter in the web.xml file. The default is *.action, and it should be changed to /*;
7. In the applicationContext.xm file, you need to configure: sessionFactory, hibernate entity class, hibernateTemplate template, data source dataSource, and spring scanner (including hibernateContext.xml);
8. Each class must add corresponding annotations, and the methods in Action must also be added.
Download the instance source code: http://xiazai.VeVB.COM/201610/yuanma/SSHzhuce(VeVB.COM).rar
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.