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操作。当然还有许多不足之处还望轻喷!

时间: 2024-10-13 18:02:44

Spring-SpringMVC-Hibernate整合的相关文章

Spring mvc 源码 和 Spring+springmvc+hibernate整合源码

本来想着再写下spring+springmvc+hibernate整合的文章 暂时就不写了 直接附上源码,有需要的直接下载看吧.还有前面文章中的springmvc源码  前面文章只是简单的说了下 搭建环境 访问页面成功.这个源码中有模拟的增删改查和文件上传,转换json 实体类验证等功能.有问题可以留言我. http://download.csdn.net/detail/qinyanbin123/8631175 springmvc源码下载地址 http://download.csdn.net/d

Spring MVC基础知识整理?Spring+SpringMVC+Hibernate整合操作数据库

概述 Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据.Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD.Hibernate使用方便,配置响应的XML文件即可.由于spring3.x,基于asm的某些特征,而这些asm还没有用jdk8编译,所以采用Spring 3+JDK8就会报错,提示错误信息( java.lang.IllegalArgumentException),具体解决方案有:1.Spring 3+JDK7

spring+springmvc+hibernate整合实例

上篇博文中写了spring与springmvc的整合,而这一篇则是又加上了hibernate. 与上次一样,这一次仍然是先导入jar包,这一次则要加入hibernate中的jar包,如下图所示: 同时再新建两个源文件夹,一个为config,一个为test,分别存放配置文件与测试用例,现在来进行spring,springmvc以及hibernate的配置. 新建spring-hibernate.xml,applicationContext.xml,springmvc.xml,hibernate.c

Spring+SpringMVC+Hibernate整合笔记(一)项目结构与配置

(1) entity 包 : 放置项目中的实体类(一个表一个类),pojo (2) util 工具包: 各种工具类(StringHelper类) ----M----- (3) dao 接口包: 各种操作接口类(ICRM_UserDao) (4) dao.impl 实现接口包:各种实习操作接口的实现类(CRM_UserDaoImpl) (5) service 接口包: 业务实现的接口(ICRM_UserService) (6)service.impl 实现业务接口的实现类(CRM_UserServ

SpringMVC与Spring、Hibernate整合

本文采用正向工程1.搭建工程        工程名称:mvcsh2.添加支持的jar包        1).spring-3.2.0.jar 注:struts相关的jar不需要 \libs\*.jar com.springsource.org.aopalliance-1.0.0.jar            com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar            commons-logging.jar        2).

Spring+SpringMVC+Hibernate 与 shiro 整合步骤

通过这篇文章你可以了解到: SSH 三大框架(spring + springMVC + Hiberante) 与 shiro 安全验证框架如何整合: 通过一个示例,快速理解 shiro 框架. [TOC] 1. 业务需求分析 用户 N - 角色 N - 权限 N 我们可以想象一下,在平时工作中的职务,比如:业务经理,部门主管等,他们拥有很多的权力,而一个公司中不会只有一个业务经理,也不会只有一个部门主管,如果我们要给不同的人分配职务权力时,每次都是具体的条条框框去分配,人累心也累.而如果我们事先

springMVC系列之(四) spring+springMVC+hibernate 三大框架整合(转)

https://blog.csdn.net/lishehe/article/details/38356261 基于spring+springmvc+hibernate的maven项目搭建 https://blog.csdn.net/fancy_t/article/details/70989754 原文地址:https://www.cnblogs.com/1987721594zy/p/9708567.html

SpringMVC+hibernate整合小例子,用户的增删查改

SpringMVC+hibernate整合小例子,用户的增删查改 对于使用框架写项目,我的第一反应的把所有需要的jar文件引入. 因为我用的是JDK1.8,当使用spring3.2 注解的时候会出现问题,所以最终使用的spring4.0.  hibernate使用的版本为4.0 .至于一些依赖包的版本就是看别人的资料拿的. 然后看下整体的项目结构 第一步写的是web.xml配置文件,当然有写东西是后面加上去的,不是一步到位的,比如说控制post方式的乱码.以及无法时候JS文件等一些静态文件,后面

spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory

Hibernate 3.6以上版本在用junit测试时会提示错误: Unable to get the default Bean Validation factory spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory  ,是因为新版hibernate用到新的jar包造成的,默认会自动找验证包,吴国不需要这一步,可以在spring整合hibernate的配置节点中添加如下标红属性: <bean id="sessio

Spring与Hibernate整合,实现Hibernate事务管理

1.所需的jar包 连接池/数据库驱动包 Hibernate相关jar Spring 核心包(5个) Spring aop 包(4个) spring-orm-3.2.5.RELEASE.jar                 [spring对hibernate的支持] spring-tx-3.2.5.RELEASE.jar                     [事务相关] 2.配置文件 Product.hbm.xml <?xml version="1.0" encoding=