SpringMVC+Hibernate+Spring integration example (1)

SpringMVC is another beautiful web framework. It keeps pace with Struts2. Struts was born early and occupies a certain advantage. I made a simple example in the blog "Struts1+Hibernate+Spring Integration Example" to introduce the basic construction method of SSH1. Struts2 is developed based on Struts1. There is no example of SSH2 posted in the blog. Only the similarities and differences between Struts1 and Struts2 are compared. Through comparison, the construction of SSH2 is basically no problem. The following is also a simple application example to introduce the basic usage of SpringMVC. The next blog will also sort out some similarities and differences between Struts2 and SpringMVC. By sorting out the connection with old knowledge, the cost of learning is reduced and it takes a very short time. You can learn about a seemingly new technology, but its essence has not changed.

Let's start the example. The requirement of this example is to add, delete, modify and check user information. First create a web project test_ssh, the directory structure and the required Jar package are as follows:




Create a User entity class, put it under the Entity package, and use annotations:

[java] view plaincopy
package com.tgb.entity; 
 
import javax.persistence .Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table; 
 
import org.hibernate.annotations.GenericGenerator; 
 
@Entity 
@Table(name="T_USER") 
public class User { 
 
    @Id 
    @GeneratedValue(generator="system-uuid") 
    @GenericGenerator(name = "system-uuid",strategy="uuid") 
    @Column(length=32) 
    private String id; 
     
    @Column(length=32) 
    private String userName; 
     
    @Column(length=32) 
    private String age; 
 
    public String getId() { 
        return id; 
    } 
 
    public void setId(String id) { 
        this.id = id; 
    } 
 
    public String getUserName() { 
        return userName; 
    } 
 
    public void setUserName(String userName) { 
        this.userName = userName; 
    } 
 
    public String getAge() { 
        return age; 
    } 
 
    public void setAge(String age) { 
        this.age = age; 
    } 
     

This article will basically use annotations about SpringMVC, first configure the data source and The transaction spring-common.xml is placed under the config.spring package:

[html] view plaincopy
<?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.xsd"> 
     
    <!-- 配置数据源 --> 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > 
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
        <property name="url" value="jdbc:mysql://localhost/test_ssh"></property> 
        <property name="username" value="root"></property> 
        <property name="password" value="1"></property> 
    </bean> 
     
    <!-- 配置SessionFactory --> 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" /> 
        <property name="hibernateProperties"> 
            <props> 
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
                <prop key="hibernate.hbm2ddl.auto">update</prop> 
                <prop key="hibernate.show_sql">true</prop> 
                <prop key="hibernate.format_sql">true</prop> 
            </props> 
        </property> 
        <property name="annotatedClasses"> 
            <list> 
                <value>com.tgb.entity.User</value> 
            </list> 
        </property> 
    </bean> 
     
    <!-- 配置一个事务管理器 --> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
        <property name="sessionFactory" ref="sessionFactory"/> 
    </bean> 
     
    <!-- 配置事务,使用代理的方式 --> 
    <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">   
        <property name="transactionManager" ref="transactionManager"></property>   
        <property name="transactionAttributes">   
            <props>   
                <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>   
                <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>   
                <prop key="del*">PROPAGATION_REQUIRED</prop>   
                <prop key="*">PROPAGATION_REQUIRED</prop>   
            </props>   
        </property>   
    </bean>  
</beans> 
and then configure the content about SpringMVC, There are comments in the following configurations, so I won't repeat them. spring-mvc.xml is placed under the config.spring package:

[html] view plaincopy
<?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.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context- 3.2.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 
     
    <!-- Annotation scan package --> 
    < context:component-scan base-package="com.tgb" /> 
 
    <!-- Enable annotation--> 
    <mvc:annotation-driven /> 
     
    <!-- Access to static resources (js/image)--> 
    < mvc:resources location="/js/" mapping="/js/**"/> 
 
    <!-- define view resolver -->   
    <bean id="viewResolver" class="org.springframework.web.  servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="/"></property> 
        <property name="suffix" value=".jsp"></property> 
    </bean> 
</beans> 
完成这些共用的配置之后,来配置web项目起点web.xml:

[html] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 
  <display-name>json_test</display-name> 
  <welcome-file-list> 
    <welcome-file>login.jsp</welcome-file> 
  </welcome-file-list> 
   
  <!-- 加载所有的配置文件 --> 
  <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath*:config/spring/spring-*.xml</param-value> 
  </context-param> 
   
  <!-- 配置Spring监听 --> 
  <listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener> 
   
  <!-- 配置SpringMVC --> 
  <servlet> 
    <servlet-name>springMVC</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
        <param-name>contextConfigLocation</param-name> 
        <param-value>classpath*:config/spring/spring-mvc.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
  </servlet> 
  <servlet-mapping> 
    <servlet-name>springMVC</servlet-name> 
    <url-pattern>/</url-pattern> 
  </servlet-mapping> 
   
  <!-- 配置字符集 --> 
  <filter> 
    <filter-name>encodingFilter</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> 
  <filter-mapping> 
    <filter-name>encodingFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
   
  <!-- 配置Session --> 
  <filter> 
    <filter-name>openSession</filter-name> 
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> 
  </filter> 
  <filter-mapping> 
    <filter-name>openSession</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
</web-app> 
Readers need to download the jquery package and put it under the js package in the webContent folder. Then create several test pages as follows:

Login.jsp, the entry interface of the project.

[html] view plaincopy
<h5><a href="/test_ssh/user/getAllUser">Enter the user management page</a></h5> 
Index.jsp, the main interface of user management

[html] view plaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/ jsp/jstl/core" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html > 
<head> 
<script type="text/javascript" src="../js/jquery-1.7.1.js">< 


<script type="text/javascript"> 
    function del(id){ 
        $.get("/test_ssh/user/delUser?id=" + id,function(data){ 
            if("success" == data.result){ 
                alert("删除成功"); 
                window.location.reload(); 
            }else{ 
                alert("删除失败"); 
            } 
        }); 
    } 
</script> 
</head> 
<body> 
    <h6><a href="/test_ssh/user/toAddUser">添加用户</a></h6> 
    <table border="1"> 
        <tbody> 
            <tr> 
                <th>name</th>                  <th>action</th> 
                <th>age</th> 

            </tr> 
            <c:if test="${!empty userList }"> 
                <c:forEach items="${userList }" var="user"> 
                    <tr> 
                        <td>${user.userName }</td> 
                        <td>${user.age }</td> 
                        <td> 
                            <a href="/test_ssh/user/getUser?id=${user.id }">编辑</a> 
                            <a href="javascript:del('${user.id }')">删除</a> 
                        </td> 
                    </tr>              
                </c:forEach> 
            </c:if> 
        </tbody> 
    </table> 
</body> 
</html> 
addUser.jsp,添加用户界面

[html] view plaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
<script type="text/javascript"> 
    function addUser(){ 
        var form = document.forms[0]; 
        form.action = "/test_ssh/user/addUser"; 
        form.method="post"; 
        form.submit(); 
    } 
</script> 
</head> 
<body> 
    <h1>添加用户</h1> 
    <form action="" name="userForm"> 
        姓名:<input type="text" name="userName"> 
        年龄:<input type="text" name="age"> 
        <input type="button" value="添加" onclick="addUser()"> 
    </form> 
</body> 
</html> 
editUser.jsp,修改用户信息界面。

[html] view plaincopy
<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<script type="text/javascript" src="../js/jquery-1.7.1.js"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
    <h1>编辑用户</h1> 
    <form action="/test_ssh/user/updateUser" name="userForm" method="post"> 
        <input type="hidden" name="id" value="${user.id }"> 
        姓名:<input type="text" name="userName" value="${user.userName }"> 
        年龄:<input type="text" name="age" value="${user.age }"> 
        <input type="submit" value="编辑" > 
    </form> 
</body> 
</html> 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326760345&siteId=291194637