Spring+SpringMVC+Hibernate简单整合(转)

时间:2022-03-10 22:44:09

SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,下面同样做一个简单的应用实例,介绍SpringMVC的基本用法,接下来的博客也将梳理一下Struts2和SpringMVC的一些异同,通过梳理和旧知识的联系,让学习的成本变低,花很短的时间就可以了解一门貌似新的技术,其实本质没变。

原文http://langgufu.iteye.com/blog/2088355

下面开始实例,这个实例的需求是对用户信息进行增删改查。首先创建一个web项目test_ssh,目录结构及需要的Jar包如下图:

创建一个User实体类,放在Entity包下,采用注解的方式:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.entity;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. import javax.persistence.Table;
  7. import org.hibernate.annotations.GenericGenerator;
  8. @Entity
  9. @Table(name="T_USER")
  10. public class User {
  11. @Id
  12. @GeneratedValue(generator="system-uuid")
  13. @GenericGenerator(name = "system-uuid",strategy="uuid")
  14. @Column(length=32)
  15. private String id;
  16. @Column(length=32)
  17. private String userName;
  18. @Column(length=32)
  19. private String age;
  20. public String getId() {
  21. return id;
  22. }
  23. public void setId(String id) {
  24. this.id = id;
  25. }
  26. public String getUserName() {
  27. return userName;
  28. }
  29. public void setUserName(String userName) {
  30. this.userName = userName;
  31. }
  32. public String getAge() {
  33. return age;
  34. }
  35. public void setAge(String age) {
  36. this.age = age;
  37. }
  38. }

本篇关于SpringMVC基本都会采用注解的方式,首先配置好数据源以及事务spring-common.xml,放在config.spring包下:

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd">
  8. <!-- 配置数据源 -->
  9. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
  10. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  11. <property name="url" value="jdbc:mysql://localhost/test_ssh"></property>
  12. <property name="username" value="root"></property>
  13. <property name="password" value="1"></property>
  14. </bean>
  15. <!-- 配置SessionFactory -->
  16. <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  17. <property name="dataSource" ref="dataSource" />
  18. <property name="hibernateProperties">
  19. <props>
  20. <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  21. <prop key="hibernate.hbm2ddl.auto">update</prop>
  22. <prop key="hibernate.show_sql">true</prop>
  23. <prop key="hibernate.format_sql">true</prop>
  24. </props>
  25. </property>
  26. <property name="annotatedClasses">
  27. <list>
  28. <value>com.tgb.entity.User</value>
  29. </list>
  30. </property>
  31. </bean>
  32. <!-- 配置一个事务管理器 -->
  33. <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  34. <property name="sessionFactory" ref="sessionFactory"/>
  35. </bean>
  36. <!-- 配置事务,使用代理的方式 -->
  37. <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
  38. <property name="transactionManager" ref="transactionManager"></property>
  39. <property name="transactionAttributes">
  40. <props>
  41. <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
  42. <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
  43. <prop key="del*">PROPAGATION_REQUIRED</prop>
  44. <prop key="*">PROPAGATION_REQUIRED</prop>
  45. </props>
  46. </property>
  47. </bean>
  48. </beans>

然后配置关于SpringMVC的内容,下面配置中都有注释说明,就不再赘述,spring-mvc.xml放在config.spring包下:

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12. <!-- 注解扫描包 -->
  13. <context:component-scan base-package="com.tgb" />
  14. <!-- 开启注解 -->
  15. <mvc:annotation-driven />
  16. <!-- 静态资源(js/image)的访问 -->
  17. <mvc:resources location="/js/" mapping="/js/**"/>
  18. <!-- 定义视图解析器 -->
  19. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/"></property>
  21. <property name="suffix" value=".jsp"></property>
  22. </bean>
  23. </beans>

完成这些共用的配置之后,来配置web项目起点web.xml:

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <display-name>json_test</display-name>
  4. <welcome-file-list>
  5. <welcome-file>login.jsp</welcome-file>
  6. </welcome-file-list>
  7. <!-- 加载所有的配置文件 -->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath*:config/spring/spring-*.xml</param-value>
  11. </context-param>
  12. <!-- 配置Spring监听 -->
  13. <listener>
  14. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  15. </listener>
  16. <!-- 配置SpringMVC -->
  17. <servlet>
  18. <servlet-name>springMVC</servlet-name>
  19. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  20. <init-param>
  21. <param-name>contextConfigLocation</param-name>
  22. <param-value>classpath*:config/spring/spring-mvc.xml</param-value>
  23. </init-param>
  24. <load-on-startup>1</load-on-startup>
  25. </servlet>
  26. <servlet-mapping>
  27. <servlet-name>springMVC</servlet-name>
  28. <url-pattern>/</url-pattern>
  29. </servlet-mapping>
  30. <!-- 配置字符集 -->
  31. <filter>
  32. <filter-name>encodingFilter</filter-name>
  33. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  34. <init-param>
  35. <param-name>encoding</param-name>
  36. <param-value>UTF-8</param-value>
  37. </init-param>
  38. <init-param>
  39. <param-name>forceEncoding</param-name>
  40. <param-value>true</param-value>
  41. </init-param>
  42. </filter>
  43. <filter-mapping>
  44. <filter-name>encodingFilter</filter-name>
  45. <url-pattern>/*</url-pattern>
  46. </filter-mapping>
  47. <!-- 配置Session -->
  48. <filter>
  49. <filter-name>openSession</filter-name>
  50. <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  51. </filter>
  52. <filter-mapping>
  53. <filter-name>openSession</filter-name>
  54. <url-pattern>/*</url-pattern>
  55. </filter-mapping>
  56. </web-app>

读者需自行下载jquery包,放到webContent文件夹下的js包下。然后创建几个测试页面,分别如下:

Login.jsp,项目的入口界面。

[html] view plaincopy
  1. <h5><a href="/test_ssh/user/getAllUser">进入用户管理页</a></h5>

Index.jsp,用户管理的主界面

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <script type="text/javascript" src="../js/jquery-1.7.1.js"></script>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Insert title here</title>
  10. <script type="text/javascript">
  11. function del(id){
  12. $.get("/test_ssh/user/delUser?id=" + id,function(data){
  13. if("success" == data.result){
  14. alert("删除成功");
  15. window.location.reload();
  16. }else{
  17. alert("删除失败");
  18. }
  19. });
  20. }
  21. </script>
  22. </head>
  23. <body>
  24. <h6><a href="/test_ssh/user/toAddUser">添加用户</a></h6>
  25. <table border="1">
  26. <tbody>
  27. <tr>
  28. <th>姓名</th>
  29. <th>年龄</th>
  30. <th>操作</th>
  31. </tr>
  32. <c:if test="${!empty userList }">
  33. <c:forEach items="${userList }" var="user">
  34. <tr>
  35. <td>${user.userName }</td>
  36. <td>${user.age }</td>
  37. <td>
  38. <a href="/test_ssh/user/getUser?id=${user.id }">编辑</a>
  39. <a href="javascript:del('${user.id }')">删除</a>
  40. </td>
  41. </tr>
  42. </c:forEach>
  43. </c:if>
  44. </tbody>
  45. </table>
  46. </body>
  47. </html>

addUser.jsp,添加用户界面

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. <script type="text/javascript">
  9. function addUser(){
  10. var form = document.forms[0];
  11. form.action = "/test_ssh/user/addUser";
  12. form.method="post";
  13. form.submit();
  14. }
  15. </script>
  16. </head>
  17. <body>
  18. <h1>添加用户</h1>
  19. <form action="" name="userForm">
  20. 姓名:<input type="text" name="userName">
  21. 年龄:<input type="text" name="age">
  22. <input type="button" value="添加" onclick="addUser()">
  23. </form>
  24. </body>
  25. </html>

editUser.jsp,修改用户信息界面。

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <script type="text/javascript" src="../js/jquery-1.7.1.js"></script>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Insert title here</title>
  10. </head>
  11. <body>
  12. <h1>编辑用户</h1>
  13. <form action="/test_ssh/user/updateUser" name="userForm" method="post">
  14. <input type="hidden" name="id" value="${user.id }">
  15. 姓名:<input type="text" name="userName" value="${user.userName }">
  16. 年龄:<input type="text" name="age" value="${user.age }">
  17. <input type="submit" value="编辑" >
  18. </form>
  19. </body>
  20. </html>

还有success.jsp和error.jsp页面,无代码,就不再展示。

框架越来越多,越来越好用,但随之而来的繁杂的、各成体系的配置怎么办?项目大了感觉注解靠谱些。

这篇接着上篇,把没贴完的代码写完,上篇主要完成了一些公共配置和界面的东西,这篇把后台的代码完成。

首先是web包下属于的control层的类UserController,这相当于Struts中的Action,是重要的类:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.web;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.annotation.Resource;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import com.tgb.entity.User;
  10. import com.tgb.manager.UserManager;
  11. @Controller
  12. @RequestMapping("/user")
  13. public class UserController {
  14. @Resource(name="userManager")
  15. private UserManager userManager;
  16. @RequestMapping("/getAllUser")
  17. public String getAllUser(HttpServletRequest request){
  18. request.setAttribute("userList", userManager.getAllUser());
  19. return "/index";
  20. }
  21. @RequestMapping("/getUser")
  22. public String getUser(String id,HttpServletRequest request){
  23. request.setAttribute("user", userManager.getUser(id));
  24. return "/editUser";
  25. }
  26. @RequestMapping("/toAddUser")
  27. public String toAddUser(){
  28. return "/addUser";
  29. }
  30. @RequestMapping("/addUser")
  31. public String addUser(User user,HttpServletRequest request){
  32. userManager.addUser(user);
  33. return "redirect:/user/getAllUser";
  34. }
  35. @RequestMapping("/delUser")
  36. public void delUser(String id,HttpServletResponse response){
  37. String result = "{\"result\":\"error\"}";
  38. if(userManager.delUser(id)){
  39. result = "{\"result\":\"success\"}";
  40. }
  41. response.setContentType("application/json");
  42. try {
  43. PrintWriter out = response.getWriter();
  44. out.write(result);
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. @RequestMapping("/updateUser")
  50. public String updateUser(User user,HttpServletRequest request){
  51. if(userManager.updateUser(user)){
  52. user = userManager.getUser(user.getId());
  53. request.setAttribute("user", user);
  54. return "redirect:/user/getAllUser";
  55. }else{
  56. return "/error";
  57. }
  58. }
  59. }

然后是属于manager包下的业务逻辑类,接口UserManager:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.manager;
  2. import java.util.List;
  3. import com.tgb.entity.User;
  4. public interface UserManager {
  5. public User getUser(String id);
  6. public List<User> getAllUser();
  7. public void addUser(User user);
  8. public boolean delUser(String id);
  9. public boolean updateUser(User user);
  10. }

实现类UserManagerImpl:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.manager;
  2. import java.util.List;
  3. import com.tgb.dao.UserDao;
  4. import com.tgb.entity.User;
  5. public class UserManagerImpl implements UserManager {
  6. private UserDao userDao;
  7. public void setUserDao(UserDao userDao) {
  8. this.userDao = userDao;
  9. }
  10. @Override
  11. public User getUser(String id) {
  12. return userDao.getUser(id);
  13. }
  14. @Override
  15. public List<User> getAllUser() {
  16. return userDao.getAllUser();
  17. }
  18. @Override
  19. public void addUser(User user) {
  20. userDao.addUser(user);
  21. }
  22. @Override
  23. public boolean delUser(String id) {
  24. return userDao.delUser(id);
  25. }
  26. @Override
  27. public boolean updateUser(User user) {
  28. return userDao.updateUser(user);
  29. }
  30. }

最后是属于dao包底下的DAO层,主要由Hibernate完成。接口UserDao:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.dao;
  2. import java.util.List;
  3. import com.tgb.entity.User;
  4. public interface UserDao {
  5. public User getUser(String id);
  6. public List<User> getAllUser();
  7. public void addUser(User user);
  8. public boolean delUser(String id);
  9. public boolean updateUser(User user);
  10. }

实现类UserDaoImpl:

[java] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. package com.tgb.dao;
  2. import java.util.List;
  3. import org.hibernate.Query;
  4. import org.hibernate.SessionFactory;
  5. import com.tgb.entity.User;
  6. public class UserDaoImpl implements UserDao {
  7. private SessionFactory sessionFactory;
  8. public void setSessionFactory(SessionFactory sessionFactory) {
  9. this.sessionFactory = sessionFactory;
  10. }
  11. @Override
  12. public User getUser(String id) {
  13. String hql = "from User u where u.id=?";
  14. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  15. query.setString(0, id);
  16. return (User)query.uniqueResult();
  17. }
  18. @Override
  19. public List<User> getAllUser() {
  20. String hql = "from User";
  21. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  22. return query.list();
  23. }
  24. @Override
  25. public void addUser(User user) {
  26. sessionFactory.getCurrentSession().save(user);
  27. }
  28. @Override
  29. public boolean delUser(String id) {
  30. String hql = "delete User u where u.id = ?";
  31. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  32. query.setString(0, id);
  33. return (query.executeUpdate() > 0);
  34. }
  35. @Override
  36. public boolean updateUser(User user) {
  37. String hql = "update User u set u.userName = ?,u.age=? where u.id = ?";
  38. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  39. query.setString(0, user.getUserName());
  40. query.setString(1, user.getAge());
  41. query.setString(2, user.getId());
  42. return (query.executeUpdate() > 0);
  43. }
  44. }

最后外加一个配置spring-beans.xml,放在config.spring包下,负责为各层依赖注入需要的对象:

[html] view plaincopySpring+SpringMVC+Hibernate简单整合(转)Spring+SpringMVC+Hibernate简单整合(转)
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd">
  8. <bean id="userDao" class="com.tgb.dao.UserDaoImpl">
  9. <property name="sessionFactory" ref="sessionFactory"></property>
  10. </bean>
  11. <bean id="userManagerBase" class="com.tgb.manager.UserManagerImpl">
  12. <property name="userDao" ref="userDao"></property>
  13. </bean>
  14. <!-- 此处为代理 -->
  15. <bean name="userManager" parent="transactionProxy">
  16. <property name="target" ref="userManagerBase"></property>
  17. </bean>
  18. </beans>

到此为止,所有的配置和代码完成,部署—运行,运行结果如下图: