1. 程式人生 > >SpringMVC+Hibernate+Spring整合例項(一)

SpringMVC+Hibernate+Spring整合例項(一)

SpringMVC又一個漂亮的web框架,他與Struts2並駕齊驅,Struts出世早而佔據了一定優勢,我在部落格《整合例項》中做了一個簡單的例項,介紹了SSH1的基本搭建方式,Struts2是根據Struts1發展而來,部落格中就沒有貼SSH2的例子,只對比了下Struts1Struts2異同,通過對比,SSH2的搭建基本不在話下了。下面同樣做一個簡單的應用例項,介紹SpringMVC的基本用法,接下來的部落格也將梳理一下Struts2SpringMVC的一些異同,通過梳理和舊知識的聯絡,讓學習的成本變低,花很短的時間就可以瞭解一門貌似新的技術,其實本質沒變。

下面開始例項,這個例項的需求是對使用者資訊進行增刪改查。首先建立一個

web專案test_ssh,目錄結構及需要的Jar包如下圖:


建立一個User實體類,放在Entity包下,採用註解的方式:

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;
	}
	
}

本篇關於SpringMVC基本都會採用註解的方式,首先配置好資料來源以及事務spring-common.xml,放在config.spring包下:

<?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>

然後配置關於SpringMVC的內容,下面配置中都有註釋說明,就不再贅述,spring-mvc.xml放在config.spring包下:

<?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">
	
	<!-- 註解掃描包 -->
	<context:component-scan base-package="com.tgb" />

	<!-- 開啟註解 -->
	<mvc:annotation-driven />
	
	<!-- 靜態資源(js/image)的訪問 -->
	<mvc:resources location="/js/" mapping="/js/**"/>

	<!-- 定義檢視解析器 -->	
	<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

<?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>

讀者需自行下載jquery包,放到webContent資料夾下的js包下。然後建立幾個測試頁面,分別如下:

Login.jsp,專案的入口介面。

<h5><a href="/test_ssh/user/getAllUser">進入使用者管理頁</a></h5>

Index.jsp,使用者管理的主介面

<%@ 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>
<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>姓名</th>
				<th>年齡</th>
				<th>操作</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,新增使用者介面

<%@ 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,修改使用者資訊介面。

<%@ 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>

還有success.jsperror.jsp頁面,無程式碼,就不再展示。

框架越來越多,越來越好用,但隨之而來的繁雜的、各成體系的配置怎麼辦?專案大了感覺註解靠譜些。

下篇繼續。