Spring-SpringMVC-Hibernate整合

由于没有使用maven所以直接看包结构吧!后续可能会带有maven的!

</pre><p></p><p>包有点多,但是不要在乎这些细节,多总比少好。</p><p>下面看配置文件</p><p>spring-common.xml(相当于applicationContext.xml)</p><p></p><pre name="code" class="html"><?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:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>

	<!--配置SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!--配置数据库方言 -->
		<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="packagesToScan">
			<list>
				<value>com.iss.model</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

<?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.iss" />

	<!-- 开启注解 -->
	<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.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*: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>WEB-INF/classes/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>


好了所有的配置文件能完成了下面看逻辑代码。


com.iss.model.User.class

package com.iss.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author dell
 * 
 */
@Entity
@Table(name = "user")
public class User {
	private int id;

	private String name;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

com.iss.dao.UserDao.class

package com.iss.dao;

import java.util.List;

import com.iss.model.User;

public interface UserDao {
	public User addUser(User user);

	public List<User> getAllUsers();

	public User getUser(int userId);

	public void deleteUser(User user);

}

com.iss.dao.impl.UserDaoImpl.class

package com.iss.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.iss.dao.UserDao;
import com.iss.model.User;

@Repository
public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public User addUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(user);
		session.flush();
		return user;
	}

	public List<User> getAllUsers() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User");
		List<User> users = query.list();
		session.flush();
		return users;
	}

	public User getUser(int userId) {
		Session session = sessionFactory.getCurrentSession();
		User user = (User) session.get(User.class, userId);
		return user;
	}

	public void deleteUser(User user) {

		Session session = sessionFactory.getCurrentSession();
		session.delete(user);
		session.flush();
	}

}

com.iss.service.UserService.class

package com.iss.service;

import java.util.List;

import com.iss.model.User;

public interface UserService {

	public User addUser(User user);

	public List<User> getAllUsers();

	public User getUser(int userId);

	public void deleteUser(User user);
}

com.iss.service.UserServiceImpl.class

package com.iss.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iss.dao.UserDao;
import com.iss.model.User;
import com.iss.service.UserService;

@Service("UserService")
public class UserServiceImpl implements UserService {

	private UserDao userDao;

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User addUser(User user) {
		// TODO Auto-generated method stub
		return userDao.addUser(user);
	}

	public List<User> getAllUsers() {
		// TODO Auto-generated method stub
		return userDao.getAllUsers();
	}

	public User getUser(int userId) {
		// TODO Auto-generated method stub
		return userDao.getUser(userId);
	}

	public void deleteUser(User user) {

		userDao.deleteUser(user);
	}

}
com.iss.controller.UserController
package com.iss.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.iss.model.User;
import com.iss.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping("/toAddUser")
	public String toAddUser() {
		return "addUser";
	}

	@RequestMapping("/toUpdateUser")
	public String toUpdateUser(int id, ModelMap modelMap) {
		User user = userService.getUser(id);
		modelMap.addAttribute("user", user);
		return "editUser";
	}

	@RequestMapping("/addUser")
	public String addUser(User user) {
		userService.addUser(user);
		return "redirect:/user/getAllUser";

	}

	@RequestMapping("/getAllUser")
	public String getAllUsers(ModelMap modelMap) {
		List<User> userList = userService.getAllUsers();
		modelMap.addAttribute("userList", userList);
		return "index";

	}

	@RequestMapping("/delUser")
	public String delUser(int id, HttpServletResponse response)
			throws IOException {
		User user = userService.getUser(id);
		System.err.println(user.getName());
		userService.deleteUser(user);
		response.getWriter().print("success");
		return null;

	}

}
下面是几个jsp页面的代码

login.jsp

<body>
	<h5>
		<a href="user/getAllUser">进入用户管理页</a>
	</h5>

</body>

index.jsp

<body>
	<h6>
		<a href="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 id="tr${user.id }">
						<td>${user.id }</td>
						<td>${user.name}</td>
						<td><a href="toUpdateUser?id=${user.id }">编辑</a> <a
							href="javascript:del(${user.id })">删除</a>
						</td>
					</tr>
				</c:forEach>
			</c:if>
		</tbody>
	</table>
</body>

其中删除用了Jquery需引用?Jquery包

<script type="text/javascript" src="../js/jQuery.js"></script>
<script type="text/javascript">
	function del(id) {
		/* $.get("delUser?id=" + id, function(data) {
			alert(data);
			if ("success" == data) {
				alert("删除成功");
				$("#tr" + id).remove();
			} else {
				alert("删除失败");
			}
		}); */

		var url = "delUser?id=" + id;
		$.ajax({
			type : "post",
			url : url,
			dataType : "text",
			success : function(data) {
				if ("success" == data) {
					alert("删除成功");
					$("#tr" + id).remove();
				} else {
					alert("删除失败");
				}

			}

		});
	}
</script>

editUser.jsp

	<h1>编辑用户</h1>
	<form action="addUser" name="userForm" method="post">
		<input type="hidden" name="id" value="${user.id }"> 姓名:<input
			type="text" name="name" value="${user.name }"> <input
			type="submit" value="编辑">
	</form>
addUser.jsp

<body>
	<h1>添加用户</h1>
	<form action="" name="userForm">
		姓名:<input type="text" name="name"> <input type="button"
			value="添加" onclick="addUser()">
	</form>
</body>

其中js代码

<script type="text/javascript">
	function addUser() {
		var form = document.forms[0];
		form.action = "addUser";
		form.method = "post";
		form.submit();
	}
</script>

以上基本完成了Spring-SpringMVC-Hibernate之间的整合并进行了基本的crud操作。当然还有许多不足之处还望轻喷!










郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。