cool hit counter SSH framework tour-spring (4)_Intefrankly

SSH framework tour-spring (4)


spring.jpg

The following SSH framework to do an integration of the three major frameworks used version number Struts2.3.x, Spring4.x, hibernate5.x.

1.Review SSH framework knowledge points


1.1 Hibernate framework

  • Hibernate's core configuration files:Database information,Hibernate information, map (math.) configure。 If you simply use Hibernate framework, core configuration file Name of the(hibernate.cfg.xml) harmony location(src following) It's all fixed.。 But in harmony Spring Time for integration, Hibernate's core configuration files name (of a thing) harmony There is no fixed requirement for location。
  • Mapping profiles for Hibernate: orm ideas, object-relational mapping. Entity class and data table mapping relationships - using orm thinking.

When the Spring framework wraps the Hibernate framework, the HibernateTemplate class is used.

1.2 Struts2 framework

  • Action operations:Action establish The three ways in which the, General use of inheritance ActionSupport come as a class establish Action kind。 configure establish struts.xml configuration file come round configure Action of interviews trails, configuration file Name of the harmony location(src following) It's all fixed.。 configure Action Class Multiple of the approach The way to use wildcards。 in use Action Class When getting the data submitted by the form, General use ServletActionContext class to get the, And property encapsulation, Model Driven, Expression Encapsulation。 (located) at Action central operating domain targets when using ServletActionContext come and get。 There are alsoStruts2 of filter configure
  • Value stack: put data into the value stack, set method and push method, define variables, generate get method. Get the data from the value stack, using Struts2 tags in jsp plus OGNL expressions to get it. label <s:propertity><s:iterator>
  • Interceptor: AOP idea and chain of responsibility pattern, custom interceptor inherits MethodFilterInterceptor class, override the methods inside the parent class, configure the interceptor and Action association.

1.3 Spring framework

  • Spring Core Configuration Files: name (of a thing) harmony There is no set requirement for location, (located) at Spring Core Configuration Files introducing in scheme bind。
  • Create object: xml configuration method.<bean id="" class="" scope=""/> ; annotation approach, four annotations, @Component, @Repostiry, @Service, @Controller.
  • attribute injection: xml configuration method.<property name="" ref=""> ; annotation approach, two annotations, @AutoWired, @Resource.
  • use ServletContext targets harmony listener, Implementing loading on server startup Spring of configuration file establish targets, configure Spring of listener, designate Spring configuration file location。
  • JdbcTemplate
  • Spring's transaction management: the xml way and the annotation way.

2.SSH framework integration


2.1 Ideas for SSH framework integration

The three-tier architecture of Java EE.png

Struts2 is responsible for interacting with interface data, path jumping, intercepting requests, and calling methods in the Service layer. Spring is responsible for object creation in the other two frameworks, implementing business logic and calling methods for data manipulation in the Dao layer. Hibernate is responsible for interacting with the database, adding, deleting, checking, etc.

2.2 SSH framework integration preparation

Create a folder and put the jar packages used in the previous three frameworks in it, and add three more jar packages. One is the integration of the entire java web project spring-web.jar , one is integrated with struts2 struts2-spring-plugin.jar, one that integrates the persistence layer framework spring-orm.jar

2.3 Spring Integration Development

This is illustrated below by adding an example of a student.

physical category

package cc.wenshixin.entity;

public class Student {
    private int id;
    private String name;
    private String sex;
     //get and set methods

physical category map configuration file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" />
        </property>
    </class>
</hibernate-mapping>

Hibernate's core configuration files

Hibernate of the database configure part c3p0 connection pool of the configure in。

<?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>
      <!--  configurehibernate -->
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
      
      <!--  Introducing the mapping file -->
      <mapping resource="cc/wenshixin/entity/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

configuration file

The first is the configuration of the web.xml file for the entire web project, in addition to the interceptor in struts2, and the location of the spring core configuration fileclasspath Write spring core configuration file location, is generally placed directly under src, in addition to configure the listener, to create Hibernate related objects when the server starts, to solve the problem of the first time to do the database operation is slow.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssh01</display-name>
  <!-- spring of configure -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:bean.xml</param-value>
  </context-param>
  
  <!-- struts2 The interceptor of the configure -->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!--  listener of configure -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

struts2 core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
  <package name="demo" extends="struts-default" namespace="/">
    <action name="studentAction" class="studentAction"></action>
  </package>
</struts>

The core configuration file for spring

Spring framework to operate JDBC is JdbcTemplate, but for other persistence layer also encapsulates the corresponding class, operating Hibernate is HibernateTemplate class, but also need to inject sessionFactory property, configure the sessionFactory object based on the c3p0 connection pool, and additionally configure transaction management.

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!--  Configuring Database Information -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--  Injecting property values -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!--  configuresessionFactory establish -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!--  Development of information for the database -->
    <property name="dataSource" ref="dataSource"></property>
    <!--  Designated use ofhibernate core configuration file location -->
    <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
  </bean>
  
  <!--  Configuring the Transaction Manager -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <!--  empty intosessionFacory targets -->
    <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
  
  <!--  Enabling transaction annotations -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!--  configurehibernateTemplate targets -->
  <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>  
  </bean>
  
  <!--  Configuring three-tier structure objects -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  
  <!--  Turn on annotation scanning -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

Dao class

package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate5.HibernateTemplate;

import cc.wenshixin.entity.Student;

public class StudentDao{
    @Resource(name="hibernateTemplate")
    private HibernateTemplate hibernateTemplate;
    
    public void add() {
        Student student = new Student();
        student.setName("james");
        student.setSex(" male");
        hibernateTemplate.save(student);
    }
}

Service Class

package cc.wenshixin.service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import cc.wenshixin.dao.StudentDao;

@Transactional
public class StudentService {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
    public void add()
    {
        System.out.println("service...");
        studentDao.add();
    }
}

Action Class

package cc.wenshixin.action;

import javax.annotation.Resource;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.service.StudentService;

public class StudentAction extends ActionSupport{
    @Resource(name="studentService")
    private StudentService studentService;
    
    @Override
    public String execute() throws Exception {
        System.out.println("action...");
        studentService.add();
        return NONE;
    }
}

interviews http://localhost:8080/ssh01/studentAction.action

2.3 SSH sub-module development

In development, Usually to be opened in modules, That is, the core of the configuration file The contents of the split in, at the core configuration file contains other configuration file, Reducing the impact on the core configuration file Changes to the, Break a project into smaller modules, Developed with multiple people。

The following is illustrated by an example of a form submission of student information.

physical category

package cc.wenshixin.entity;

public class Student {
     private String id;  /Student Number
     private String name;  // Name
     private String banji;  // Classes
     //get and set methods

Mapping file for entity classes

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="java.lang.String">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="banji" type="java.lang.String">
            <column name="banji" />
        </property>
    </class>
</hibernate-mapping>

total web project-specific configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssh02</display-name>
  
  <!-- Spring Core Configuration -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  
  <!--  filter -->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!--  listener -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Dao class

establish an Dao class interfaces, other Dao class Implement this class in the approach。

package cc.wenshixin.dao;

public interface AbstractDao {
    public void add(Object object);
}
package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate5.HibernateTemplate;

import cc.wenshixin.entity.Student;

public class StudentDao implements AbstractDao{
    @Resource(name="hibernateTemplate")
    private HibernateTemplate hibernateTemplate;

    @Override
    public void add(Object object) {
        System.out.println("dao。。。");
        hibernateTemplate.save((Student)object);
    }
}

Service Class

package cc.wenshixin.service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import cc.wenshixin.dao.StudentDao;
import cc.wenshixin.entity.Student;

@Transactional
public class StudentService {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
    public void add(Student student)
    {
        System.out.println("service。。。");
        studentDao.add(student);
    }
}

Action Class

package cc.wenshixin.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;
import cc.wenshixin.service.StudentService;

public class StudentAction extends ActionSupport {
    @Resource(name="studentService")
    private StudentService studentService;
    private HttpServletRequest request = ServletActionContext.getRequest();
    
    public String add() throws Exception 
    {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String banji = request.getParameter("banji");
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setBanji(banji);
        System.out.println("action。。。");
        studentService.add(student);
        return NONE;
    }
}

incommunicado establish A package to hold the non-core configuration file,spring harmony struts2 core configuration file Still placed in src directory, Also in spring in configure hibernate of options harmony Introducing the mapping file, It can no longer be written separately Hibernate of configuration file。

student-spring.xml

release student pertinent Action Class, Service Class,DAO kind。

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!--  Configuration objects -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction" scope="prototype"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
</beans>

student-struts.xml

release Action Class hit the target approach of configure

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
  <package name="student" extends="struts-default" namespace="/">
    <action name="addStudent" class="studentAction" method="add"></action>
  </package>
</struts>

Spring Core Configuration Files

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
        
  <!--  Configuring Database Information -->      
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--  Injecting property values -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!--  configuresessionFactory establish -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <!--  Information on the specified database -->
    <property name="dataSource" ref="dataSource"></property>  
    <!--  configurehibernate options -->
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
      </props>
    </property>
    <!--  Introducing the mapping file -->
    <property name="mappingResources">
      <list>
        <value>cc/wenshixin/entity/Student.hbm.xml</value>
      </list>
    </property>
  </bean>
  
  <!--  Configuring the Transaction Manager -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <!--  empty intosessionFactory targets -->
    <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
  
  <!--  Enabling transaction annotations -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!--  Configuration objects -->
  <bean id="studentAction" class="cc.wenshixin.action.StudentAction"></bean>
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  
  <!--  Enabling property injection annotations -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
    
  <!--  configurehibernateTemplate targets -->
  <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>  
  </bean>

  <!--  introduce targets configuration file -->
  <import resource="classpath:cc/wenshixin/config/student-spring.xml"/>
</beans>

Struts core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
  <package name="default" extends="struts-default" namespace="/"></package>

  <include file="cc/wenshixin/config/student-struts.xml"></include>
</struts>

Structure of the entire project

Project directory structure.png

log4j of configuration file It's not necessary., However, it is recommended to use, Easy to find errors。

The SSH framework journey has only just begun here.


Recommended>>
1、SomeWaysToCreateAnInteractiveShellOnLinux
2、Are digital currencies virtual coins BitEast takes a look at digital currencies
3、MeritMS Automatic Database Backup with beego
4、Deques partial member function analysis about this class Baidu has a lot of analysis but not its function introduction
5、Longest common subsequence and longest common substring

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号