首页 > 代码库 > Spring-SpringMVC-Hibernate整合

Spring-SpringMVC-Hibernate整合

因为没有使用maven所以直接看包结构吧!兴许可能会带有maven的!

包有点多,可是不要在乎这些细节,多总比少好。以下看配置文件spring-common.xml(相当于applicationContext.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">

	<!--配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value=http://www.mamicode.com/"com.mysql.jdbc.Driver">>
另一个就是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=http://www.mamicode.com/"/">>
最后是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=http://www.mamicode.com/"user/getAllUser">进入用户管理页>
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=http://www.mamicode.com/"../js/jQuery.js"></script>>
editUser.jsp

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

<body>
	<h1>加入用户</h1>
	<form action="" name="userForm">
		姓名:<input type="text" name="name"> <input type="button"
			value=http://www.mamicode.com/"加入" onclick="addUser()">>
当中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操作。当然还有很多不足之处还望轻喷!










Spring-SpringMVC-Hibernate整合