Web – SSH framework integration

The project directory structure is as follows:

1. Import jar package

<dependencies>
    <!--hibernate package-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
    <!-- Add mysql driver dependency -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.12</version>
    </dependency>
    <!--log package-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.1</version>
    </dependency>
    <!--spring related packages-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <!--aop-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <!--Servlet related packages-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>
<build>
    <finalName>ssh-test01</finalName>
    <!--To configure this resource path, otherwise the xml file cannot be found-->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

Dao and entity classes

Dao and entity classes are related parts of hibernate
Entity class Dept

package com.ssh.pojo;
public class Dept {<!-- -->
    private Integer id;
    private String name;
    //getter/setter method slightly
}

Mapping file Dept.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ssh.pojo.Dept" table="DEPT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" precision="10" scale="0"/>
            <generator class="identity"/>
        </id>
        <property name="name" type="java. lang. String">
            <column name="NAME" length="20"/>
        </property>
    </class>
</hibernate-mapping>

Entity class Employee

package com.ssh.pojo;

public class Employee {<!-- -->
    private Integer id;
    private String name;
    private Dept dept;
    //getter/setter method slightly
}

Mapping file Employee.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ssh.pojo.Employee" table="EMPLOYEE">
        <id name="id" type="java.lang.Integer">
            <column name="ID" precision="10" scale="0"/>
            <generator class="identity"/>
        </id>
        <property name="name" type="java. lang. String">
            <column name="NAME" length="20"/>
        </property>
        <!--many to one-->
        <many-to-one name="dept" class="com.ssh.pojo.Dept">
            <column name="DEPT_ID"/>
        </many-to-one>
    </class>
</hibernate-mapping>

EmployeeDAO

package com.ssh.dao;

import com.ssh.pojo.Employee;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

//HibernateDaoSupport is a class provided by Spring, which encapsulates Hibernate's Session
public class EmployeeDAO extends HibernateDaoSupport {<!-- -->
    //Add to
    public void addEmployee(Employee emp) {<!-- -->
        super.getHibernateTemplate().save(emp);
    }

    //Condition query
    public List<Employee> getEmpByCriteria(DetachedCriteria criteria) {<!-- -->
        return (List<Employee>) super.getHibernateTemplate().findByCriteria(criteria);
    }
}

DeptDAO

package com.ssh.dao;

import com.ssh.pojo.Dept;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class DeptDAO extends HibernateDaoSupport {<!-- -->

    public List<Dept> getDeptList() {<!-- -->
        return (List<Dept>) super.getHibernateTemplate().find("from Dept", null);
    }
}

3. Integration of Hibernate and Spring

When Hibernate and Spring are integrated, Spring is mainly responsible for managing Hibernate’s Session and transactions
Configure in spring-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!--spring management data source-->
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- Configure hibernate's SessionFactory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- hibernate configuration information -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate. show_sql">true</prop>
                <prop key="hibernate. format_sql">true</prop>
            </props>
        </property>
        <!--You can also write a separate hibernate configuration file -->
        <!--<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>-->
        <!--Scan the package where the mapping file is located-->
        <!--<property name="mappingLocations" value="classpath:com/ssh/pojo/*.hbm.xml"/>-->
        <!-- Each file can be configured separately -->
        <property name="mappingResources">
            <list>
                <value>com/ssh/pojo/Employee.hbm.xml</value>
                <value>com/ssh/pojo/Dept.hbm.xml</value>
            </list>
        </property>
    </bean>
    <!-- Configure transaction manager -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--Transaction Enhancement-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- Propagation behavior, matching the method name -->
            <tx:method name="add*" rollback-for="Exception"/>
            <tx:method name="delete*" rollback-for="Exception"/>
            <tx:method name="update*" rollback-for="Exception"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="do*" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
    <!-- Provide transaction enhancement through AOP configuration, so that all methods of all beans under the service package have transactions -->
    <aop:config>
        <aop:pointcut id="serviceMethod"
                      expression="execution(* com.ssh.service..*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>

    <bean id="employeeDAO" class="com.ssh.dao.EmployeeDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="deptDAO" class="com.ssh.dao.DeptDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
</beans>

Database configuration file jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/database?characterEncoding=utf-8
jdbc.username=Username
jdbc.password=password
Log file log4j.properties
log4j.rootLogger=DEBUG, stdout,

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

4, Service

EmployeeService

package com.ssh.service;

import com.ssh.dao.EmployeeDAO;
import com.ssh.pojo.Employee;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {<!-- -->
    @Autowired
    private EmployeeDAO employeeDAO;

    public void addEmployee(Employee emp) {<!-- -->
        employeeDAO. addEmployee(emp);
    }

    public List<Employee> getEmpByCriteria(DetachedCriteria criteria) {<!-- -->
        return employeeDAO. getEmpByCriteria(criteria);
    }
}

DeptService

package com.ssh.service;

import com.ssh.dao.DeptDAO;
import com.ssh.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptService {<!-- -->
    @Autowired
    private DeptDAO deptDAO;

    public List<Dept> getDeptList(){<!-- -->
        return deptDAO. getDeptList();
    }
}

Configure the scan of Service in spring-config.xml:

<context:component-scan base-package="com.ssh.service">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>

5, Controller

Controller is part of SpringMVC:

package com.ssh.controller;

import com.ssh.pojo.Dept;
import com.ssh.pojo.Employee;
import com.ssh.service.DeptService;
import com.ssh.service.EmployeeService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {<!-- -->
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;

    @RequestMapping("/list.html")
    public String list(Employee employee, Model model) {<!-- -->
        //Encapsulate query conditions
        DetachedCriteria criteria=DetachedCriteria.forClass(Employee.class);
        if(employee.getName()!=null & amp; & amp;employee.getName().trim().length()>0){<!-- -->
            criteria.add(Restrictions.like("name","%" + employee.getName() + "%"));
        }
        model.addAttribute("employeeList", employeeService.getEmpByCriteria(criteria));
        return "/emp_list.jsp";
    }

    // go to add employee page
    @RequestMapping("/go_add.html")
    public ModelAndView goAdd() {<!-- -->
        List<Dept> deptList = deptService. getDeptList();
        return new ModelAndView("/emp_add.jsp", "deptList", deptList);
    }

    @RequestMapping("/add.html")
    public String add(Employee employee) {<!-- -->
        employeeService. addEmployee(employee);
        //Jump to the list page after adding successfully
        return "redirect:/emp/list.html";
    }

}

SpringMVC-servlet.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
    <!-- Start annotations, register services -->
    <mvc:annotation-driven/>

    <!-- Start automatic scanning -->
    <context:component-scan base-package="com.ssh.controller">
        <!-- Make package scanning rules, only scan JAVA classes annotated with @Controller -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-config.xml</param-value>
    </context-param>
    <!--Configure the listener to load the Spring configuration when starting the Web container-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<!--Process Chinese garbled characters-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
    <!--Hibernate lazy loading problem-->
    <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>
    <!--Configure DispatcherServlet -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

6. Page

emp_add.jsp

<form action="/emp/add.html" method="post">
    Employee name: <input type="text" name="name"/><br/>
    Department: <select name="dept.id">
    <c:forEach items="${deptList}" var="dept">
        <option value="${dept.id}">${dept.name}</option>
    </c:forEach>
</select><br/>
    <input type="submit" value="submit"/>
</form>

operation result

emp_list.jsp

<form action="/emp/list.html" method="post">
    Employee name: <input type="text" name="name"/>
    <input type="submit" value="Search"/>
</form>
<table>
    <tr>
        <td>id</td>
        <td>Name</td>
        <td>Department</td>
    </tr>
    <c:forEach items="${employeeList}" var="emp">
        <tr>
            <td>${emp.id}</td>
            <td>${emp.name}</td>
            <td>${emp.dept.name}</td>
        </tr>
    </c:forEach>
</table>

operation result