An article on understanding struts 2 + hibernate + spring and ssh integration framework

Keywords: Hibernate Spring ssh Struts

This article will explain based on Maven project. If you don't understand maven, you can refer to the previous article published  

Rely on the downloaded Maven website: https://mvnrepository.com/

 

Struts2

  What is struts?

A web application framework designed based on mvc pattern is an upgraded version of struts 1, which realizes the function of servlet and controls page Jump.

Usage:

1. Set up the environment and import relevant dependency packages in pom.xml

<properties>
	   <junit.version>3.8.1</junit.version>
	   <mysql.version>5.1.44</mysql.version>
	   <struts.version>2.5.13</struts.version>
	   <jstl.version>1.2</jstl.version>
	   <taglibs.version>1.1.2</taglibs.version>
	</properties>
  <dependencies>
        <!-- junit unit testing -->
        <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>  
		</dependency>
		<!-- Database connection -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		<!-- struts2 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts.version}</version>
		</dependency>
		<!-- jstl Standard label Library -->
       <dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${taglibs.version}</version>
		</dependency>
  </dependencies>

2. Configure struts.xml (core configuration file)

  Here, you can use struts-base.xml to save the basic reference content, and then import struts-base into struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--This code is from struts of jar Found in package struts-2.5.dtd Import-->
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <!-- Does it support internationalization(chinese) -->
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<!-- Use development mode -->
	<constant name="struts.devMode" value="true" />
	<!-- Turn on hot loading -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- Turn on hot loading  -->
	<constant name="struts.i18n.reload" value="true" />
	<!-- Use dynamic method -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <!-- Define a basic package and reference it in other packages you need-->
	<package name="base" extends="struts-default" abstract="true">
		<global-allowed-methods>regex:.*</global-allowed-methods>
	</package>
</struts>

  After rebuilding a struts-sys.xml, configure the required content and jump path in it, as follows

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <!--inherit struts-base.xml Packages defined in-->
    <package name="test" extends="base">
       <action name="book_*" class="com.zking.action.BookAction" method="{1}">
           <result name="index">index.jsp</result>
           <result name="success" type="redirectAction">/book_selAll</result>
           <result name="goUpdate" type="redirect">/update.jsp</result>
           <result name="add" type="redirect">/addBook.jsp</result>
       </action>
    </package>
</struts>

  3. Development

    3.1Action does not need to specify a parent class (ActionSupport),

      Definition of business method

      public String xxx();//execute
          Note 1: enable dynamic method call              

    3.2 parameter assignment
            Define properties in Action and provide get/set methods
          userName, getUserName/setUserName

hibernate

What is hibernate (from China)?

  Hibernate is an open source object relational mapping framework. It encapsulates JDBC with very lightweight objects. It establishes a mapping relationship between POJO and database tables. It is a fully automatic orm framework. Hibernate can automatically generate and execute SQL statements, so that Java programmers can use object programming thinking to manipulate the database at will.   Hibernate can be used in any situation where JDBC is used, not only in Java client programs, but also in Servlet/JSP Web applications. The most revolutionary thing is that hibernate can replace CMP in the Java EE architecture of EJB application and complete the task of data persistence.

ORM framework / persistence layer framework

Object relational mapping   Relation   Mapping, or ORM for short, or O/RM, or O/R   Mapping) is a program technology used to realize the conversion between data of different types of systems in object-oriented programming language.

Basic usage:

1. Add hibernate dependency in pom.xml (version 5.12.final is recommended)

2. Add hibernate.cfg.xml (core configuration file) in Hibernate directory as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <!-- Database related configuration -->
      <property name="connection.username">root</property>
      <property name="connection.password">123</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/T264?useUnicode=true&amp;characterEncoding=UTF-8</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <!-- dialect  -->
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
      
      <!-- Debugging related configuration -->
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      
      <!-- Enable L2 cache -->
      <property name="hibernate.cache.use_second_level_cache">true</property>
      <!-- Enable query cache -->
      <property name="hibernate.cache.use_query_cache">true</property>
      <!-- EhCache drive -->
      <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
      
    <!-- Register the entity class mapping file -->
      <mapping resource="mapping/User.hbm.xml"/>
      <mapping resource="mapping/Order.hbm.xml"/>
      <mapping resource="mapping/OrderItem.hbm.xml"/>
      <mapping resource="mapping/TreeNode.hbm.xml"/>
      <mapping resource="mapping/Book.hbm.xml"/>
      <mapping resource="mapping/BookCategory.hbm.xml"/>
    </session-factory>
      
</hibernate-configuration>

3. Every time you create a table, you should configure its entity mapping file. Take the Book table as an example to create Book.hbm.xml  

Note: after configuration, register the entity class mapping file in the hibernate core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class table="t_book" name="com.zking.entity.Book">
       <id name="bookId" type="java.lang.Integer">
       <column name="book_id"/>
       <generator class="increment"/>
     </id> 
     <property name="bookName" type="java.lang.String">
       <column name="book_name"/>
     </property>
     <property name="price" type="java.lang.Double">
       <column name="price"/>
     </property>
    
     <!--Used to configure the primary foreign key relationship between tables--> 
     <set name="bookCategories" table="t_book_category">
         <key column="bid"/>
         <many-to-many column="cid" class="com.zking.entity.BookCategory"></many-to-many>
     </set>
    </class>
</hibernate-mapping>

  4. How to use hibernate to complete CRUD operations
  4.1 CRUD operation steps
    4.1.1 read configuration
    4.1.2 create SessionFactory
    4.1.3 open Session
    4.1.4 start transaction
    4.1.5 CURD
    4.1.6 commit transaction / rollback transaction
    4.1.7 close Session

  4.2 precautions
      4.2.1 hibernate uses manual transactions by default, so it must display the start and commit transactions
      4.2.2 when deleting, you must query first and then delete

Spring 

  What is spring and what can it do?

  Spring is an open source framework created by Rod Johnson. It is created to solve the complexity of enterprise application development.
    Spring uses basic JavaBean s to do things that previously could only be done by EJB s.
    However, the use of Spring is not limited to server-side development. From the perspective of simplicity, testability and loose coupling, any Java application can benefit from Spring.
    Objective: to solve the complexity of enterprise application development
    Function: use basic JavaBean s instead of EJB s, and provide more enterprise application functions
    Scope: any Java application
    Simply put, Spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

SSH2/SSM
    1.1 intermediate layer frame and universal glue
       struts2
       spring
       hibernate
    1.2 container frame
         JavaBean
          IOC and AOP

  How to define and configure a JavaBean in spring (create a JavaBean using parameterless construction method + set method)

  1.   id: find the id of the Bean in the container (unique and cannot start with /)
  2. Class: the full class name of the bean
  3. Name: find the name of the Bean in the container (unique, allowed to start with /, allowed multiple values, separated by commas or spaces)
  4. Scope: (singleton | prototype) the default is singleton
  5. Abstract: define a bean as an abstract bean (Abstract beans cannot be instantiated). Abstract classes must be defined as abstract beans, and non abstract classes can also be defined as abstract beans
  6. Parent: specify a parent bean (inheritance relationship is required)
  7. Init method: Specifies the initialization method of the bean

Configuration of simple properties:
   8+1+3
    8 basic data + String+3 sql
   java.util.Date
     java.sql.Date
     java.sql.Time
     java.sql.Timestamp
    You can assign values through the < value > tag

Configuration of complex attributes
  5.1 JavaBean
      ref bean=""
  5.2 List or array
  5.3 Map
  5.4 Properties

Usage:

Configure the spring XML file (you can also configure spring-base.xml and import it into spring XML)

<?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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- target -->
	<bean id="bookService" class="p2.BookServiceImpl"></bean>
	
	
	<!-- Before advice  -->
	<bean id="beforeAdvice" class="p2.MyMethodBeforeAdvice"></bean>
	<!-- Post notification -->
	<bean id="afterAdvice" class="p2.MyAfterReturningAdvice"></bean>
	<!-- Around Advice  -->
	<bean id="methodInterceptor" class="p2.MyMethodInterceptor"></bean>
	<!-- Proxy object -->
	<bean id="proxybean" class="org.springframework.aop.framework.ProxyFactoryBean">
	   <property name="target">
	      <ref bean="bookService"></ref>
	   </property>
	   <property name="interceptorNames">
	      <list>
	         <value>afterAdvice</value>
	         <value>pointCutAdvice</value>
	         <value>methodInterceptor</value>
	      </list>
	   </property>
	   <property name="proxyInterfaces">
	      <list>
	        <value>p2.IBookService</value>
	      </list>
	   </property>
	</bean>
	
	<!-- Adapter -->
	<bean id="pointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
	   <property name="advice">
	        <ref bean="beforeAdvice"/>
	   </property>
	   <property name="pattern">
	      <value>.*buy</value>
	   </property>
	</bean>
</beans>

What is the ssh framework? (from popular science China)

SSH is   An integration framework of struts+spring+hibernate is a popular open source framework for Web applications 16 years ago. Different from   Secure   Shell  .

The system integrating SSH framework is divided into four layers in terms of responsibilities: presentation layer, business logic layer, data persistence layer and domain module layer, so as to help developers build Web applications with clear structure, good reusability and convenient maintenance in a short time. Struts is used as the overall infrastructure of the system, which is responsible for the separation of MVC. In the model part of Struts framework, it controls business jump, uses hibernate framework to support the persistence layer, and Spring manages struts and hibernate.

Usage: 1. Modify the spring core configuration file: realize the integration of hibernate and spring in spring-base.xml

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- to configure c3p0 Connection pool(Automatically connect and close when needed)-->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3306/T264?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="user" value="root" />
		<property name="password" value="123" />

		<!--The minimum number of connections reserved in the connection pool. -->
		<property name="minPoolSize" value="5" />

		<!--Reserved in connection pool
		Maximum number of connections. Default: 15 -->
		<property name="maxPoolSize" value="30" />

		<!--The number of connections obtained during initialization. The value should be minPoolSize And maxPoolSize between. Default: 3 -->
		<property name="initialPoolSize" value="10" />

		<!--Maximum idle time,60 If not used within seconds, the connection is discarded. If it is 0, it will never be discarded. Default: 0 -->
		<property name="maxIdleTime" value="60" />

		<!--When the connections in the connection pool are exhausted c3p0 The number of connections obtained at one time. Default: 3 -->
		<property name="acquireIncrement" value="5" />

		<!--JDBC The standard parameter used to control the data loaded in the data source PreparedStatements quantity But due to pre cached statements Belong to a single connection Instead of the entire connection pool. 
			Therefore, many factors should be considered when setting this parameter. If maxStatements And maxStatementsPerConnection If both are 0, the cache is turned off. Default: 
			0 -->
		<property name="maxStatements" value="0" />

		<!--Check free connections in all connection pools every 60 seconds. Default: 0 -->
		<property name="idleConnectionTestPeriod" value="60" />

		<!--Defines the number of repeated attempts after failed to get a new connection from the database. Default: 30 -->
		<property name="acquireRetryAttempts" value="30" />

		<!--Failure to get a connection will cause all threads waiting for the connection pool to get a connection to throw an exception. However, the data source is still valid and will be retained in the next call getConnection()Continue trying to get a connection when. 
			If set to true,Then, after the attempt to obtain the connection fails, the data source will declare that it has been disconnected and permanently closed. Default: false -->
		<property name="breakAfterAcquireFailure" value="true" />

		<!--Due to high performance consumption, please use it only when necessary. If set to true So in every connection Its validity will be verified when submitting. Recommended use idleConnectionTestPeriod 
			or automaticTestTable And other methods to improve the performance of connection test. Default: false -->
		<property name="testConnectionOnCheckout" value="false" />
	</bean>

	<!-- hibernate And spring integrate -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- specify data source -->
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<!-- appoint hibernate Related properties -->
		<property name="hibernateProperties">
			<props>
				<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.use_sql_comments">true</prop>
				<prop key="hibernate.cache.use_second_level_cache">true</prop>
				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
				</prop>
				<prop key="hibernate.cache.use_query_cache">true</prop>
			</props>
		</property>
		<!-- Specify entity mapping file -->
		<property name="mappingResources">
			<list>
				<value>mapping/Account.hbm.xml</value>
			</list>
		</property>
	</bean>

	<!-- hibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>


	<!--Declarative transaction configuration started -->
	<!--1) Turn on automatic proxy -->
	<aop:aspectj-autoproxy />

	<!--2) Transaction manager begin/commit/rollback -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!--3) Define transaction characteristics -->
	<!-- Around Advice  -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="load*" propagation="REQUIRED" read-only="true" />
			<tx:method name="list*" propagation="REQUIRED" read-only="true" />
			<tx:method name="do*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<!--4) Define pointcuts -->
	<aop:config>
		<!-- pointcut Attribute is used to define a pointcut, which is understood in four parts [* ][*..][*Service][.*(..)] -->
		<!-- A:  Return type,*Indicates that the return type is unlimited -->
		<!-- B:  Package name,*..Indicates that the package name is unlimited -->
		<!-- C:  Class or interface name,*Service The presentation class or interface must be Service ending -->
		<!-- D:  Method name and parameters,*(..)There is no limit to the method name, parameter type and number -->
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*DaoImpl.*(..))" />
	</aop:config>
	<!-- End of declarative transaction configuration -->
</beans>

Precautions for SSH integration

  1. The xml configuration file of. Struts remains basically unchanged: the integration of struts 2 is completed by changing the class attribute in the action tag to the class action reference configured in spring xml
  2. Put the contents of Hibernate's core configuration file hibernate.cfg.xml into spring.xml, configure hibernateTemplate, and put the entity class mapping file into it
  3. In java code, all bean elements defined in spring should be referenced with corresponding set/get methods

         

 

 

Posted by Akenatehm on Sun, 31 Oct 2021 02:41:41 -0700