springMVC+spring+hibernate增删改查实例

时间:2023-01-11 05:48:15

1、导包

springMVC+spring+hibernate增删改查实例

springMVC+spring+hibernate增删改查实例

2、配置文件

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  6.   
  7.     <!-- spring配置 -->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath*:config/spring-*.xml</param-value>  
  11.     </context-param>  
  12.   
  13.     <!--   配置spring启动listener入口 -->  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  16.     </listener>   
  17.       
  18.     <!-- 配置springMVC启动DispatcherServlete入口 -->  
  19.     <servlet>  
  20.         <servlet-name>springMVC</servlet-name>  
  21.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  22.         <init-param>  
  23.             <param-name>contextConfigLocation</param-name>  
  24.             <param-value>classpath:config/spring-annotation.xml</param-value>  
  25.         </init-param>  
  26.         <load-on-startup>1</load-on-startup>  
  27.     </servlet>  
  28.   
  29.     <servlet-mapping>  
  30.         <servlet-name>springMVC</servlet-name>  
  31.         <url-pattern>/</url-pattern>  
  32.     </servlet-mapping>  
  33.   
  34.     <!-- 乱码过滤器配置 -->  
  35.     <filter>  
  36.         <filter-name>CharacterEncodingFilter</filter-name>  
  37.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  38.         <init-param>  
  39.             <param-name>encoding</param-name>  
  40.             <param-value>utf-8</param-value>  
  41.         </init-param>  
  42.     </filter>  
  43.     <filter-mapping>  
  44.         <filter-name>CharacterEncodingFilter</filter-name>  
  45.         <url-pattern>/*</url-pattern>  
  46.     </filter-mapping>  
  47.       
  48.     <!-- 配置Session -->  
  49.     <filter>  
  50.         <filter-name>openSession</filter-name>  
  51.         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  52.     </filter>  
  53.     <filter-mapping>  
  54.         <filter-name>openSession</filter-name>  
  55.         <url-pattern>/*</url-pattern>  
  56.     </filter-mapping>  
  57.   
  58. </web-app>  

spring-annotation.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  7.       http://www.springframework.org/schema/context      
  8.       http://www.springframework.org/schema/context/spring-context.xsd      
  9.       http://www.springframework.org/schema/mvc      
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  11.     <context:component-scan base-package="com.xdy" />  
  12.     <mvc:annotation-driven />  
  13.   
  14.     <!-- 静态资源访问 -->  
  15.     <mvc:resources location="/img/" mapping="/img/**" />  
  16.     <mvc:resources location="/js/" mapping="/js/**" />  
  17.   
  18.     <!-- 配置解析器 -->  
  19.     <bean id="viewResolver"  
  20.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  21.         <property name="prefix" value="/" />  
  22.         <property name="suffix" value=".jsp" />  
  23.     </bean>  
  24.   
  25.     <!-- 支持上传文件 -->  
  26.     <bean id="multipartResolver"  
  27.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  28.         <property name="defaultEncoding" value="utf-8"></property>  
  29.         <property name="maxUploadSize" value="10485760000"></property>  
  30.         <property name="maxInMemorySize" value="40960"></property>  
  31.     </bean>  
  32. </beans>  
spring-hibernate.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  7.       http://www.springframework.org/schema/context      
  8.       http://www.springframework.org/schema/context/spring-context.xsd      
  9.       http://www.springframework.org/schema/mvc      
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  11.         
  12.     <!-- 配置数据源 -->  
  13.     <bean id="dataSource"  
  14.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  15.         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  16.         <property name="url" value="jdbc:mysql://localhost:3306/springmvc"></property>  
  17.         <property name="username" value="root"></property>  
  18.         <property name="password" value="root"></property>  
  19.     </bean>  
  20.       
  21.     <!-- 配置SessionFactory -->  
  22.     <bean id="sessionFactory"  
  23.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  24.         <property name="dataSource" ref="dataSource" />  
  25.         <property name="hibernateProperties">  
  26.             <props>  
  27.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  28.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  29.                 <prop key="hibernate.show_sql">true</prop>  
  30.                 <prop key="hibernate.format_sql">true</prop>  
  31.             </props>  
  32.         </property>  
  33.         <!-- 注解扫描的包 -->  
  34.         <property name="annotatedClasses">  
  35.             <list>  
  36.                 <value>com.xdy.entity.User</value>  
  37.             </list>  
  38.         </property>  
  39.     </bean>  
  40.       
  41.     <!-- 配置一个事务管理器 -->  
  42.     <bean id="transactionManager"  
  43.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  44.         <property name="sessionFactory" ref="sessionFactory" />  
  45.     </bean>  
  46.   
  47.     <!-- 配置事务,使用代理的方式 -->  
  48.     <bean id="transactionProxy"  
  49.         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true"  
  50.         abstract="true">  
  51.         <property name="transactionManager" ref="transactionManager"></property>  
  52.         <property name="transactionAttributes">  
  53.             <props>  
  54.                 <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>  
  55.                 <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>  
  56.                 <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>  
  57.                 <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>  
  58.                 <prop key="del*">PROPAGATION_REQUIRED</prop>  
  59.                 <prop key="get*">PROPAGATION_NEVER</prop>  
  60.             </props>  
  61.         </property>  
  62.     </bean>  
  63.   
  64. </beans>  
springMVC+spring+hibernate增删改查实例
spring-core.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  7.       http://www.springframework.org/schema/context      
  8.       http://www.springframework.org/schema/context/spring-context.xsd      
  9.       http://www.springframework.org/schema/mvc      
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  11.     <!-- 导入spring配置 -->  
  12.     <import  
  13.         resource="classpath*:com/xdy/spring/springAnnotation-import.xml" />  
  14. </beans>  


springAnnotation-import.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  7.       http://www.springframework.org/schema/context      
  8.       http://www.springframework.org/schema/context/spring-context.xsd      
  9.       http://www.springframework.org/schema/mvc      
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  11.     <context:component-scan base-package="com.xdy" />  
  12.     <mvc:annotation-driven />  
  13.   
  14.     <!-- 静态资源访问 -->  
  15.     <mvc:resources location="/img/" mapping="/img/**" />  
  16.     <mvc:resources location="/js/" mapping="/js/**" />  
  17.   
  18.     <!-- 配置解析器 -->  
  19.     <bean id="viewResolver"  
  20.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  21.         <property name="prefix" value="/" />  
  22.         <property name="suffix" value=".jsp" />  
  23.     </bean>  
  24.   
  25.     <!-- 支持上传文件 -->  
  26.     <bean id="multipartResolver"  
  27.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  28.         <property name="defaultEncoding" value="utf-8"></property>  
  29.         <property name="maxUploadSize" value="10485760000"></property>  
  30.         <property name="maxInMemorySize" value="40960"></property>  
  31.     </bean>  
  32. </beans>  
3、后台代码

User.java

  1. package com.xdy.entity;  
  2.   
  3. import javax.persistence.Column;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.Id;  
  7. import javax.persistence.Table;  
  8.   
  9. import org.hibernate.annotations.GenericGenerator;  
  10.   
  11. @Entity  
  12. @Table(name="t_user")  
  13. public class User {  
  14.     @Id  
  15.     @GeneratedValue(generator="system-uuid")    
  16.     @GenericGenerator(name = "system-uuid",strategy="uuid")    
  17.     @Column(length=32)    
  18.     private String id;  
  19.       
  20.     @Column(length=32)  
  21.     private String name;  
  22.       
  23.     @Column(length=32)  
  24.     private Integer age;  
  25.   
  26.     public String getId() {  
  27.         return id;  
  28.     }  
  29.   
  30.     public void setId(String id) {  
  31.         this.id = id;  
  32.     }  
  33.   
  34.     public String getName() {  
  35.         return name;  
  36.     }  
  37.   
  38.     public void setName(String name) {  
  39.         this.name = name;  
  40.     }  
  41.   
  42.     public Integer getAge() {  
  43.         return age;  
  44.     }  
  45.   
  46.     public void setAge(Integer age) {  
  47.         this.age = age;  
  48.     }  
  49.   
  50. }  
UserDao.java

  1. package com.xdy.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5.   
  6. import com.xdy.entity.User;  
  7.   
  8. public interface UserDao {  
  9.       
  10.     public void addUser(User user);  
  11.       
  12.     public boolean deleteUser(String id);  
  13.       
  14.     public boolean modifyUser(User user);  
  15.       
  16.     public List<User> getAll();  
  17.       
  18.     public User getUser(String id);  
  19. }  
UserDaoImpl.java

  1. package com.xdy.dao.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.SessionFactory;  
  7.   
  8. import com.xdy.dao.UserDao;  
  9. import com.xdy.entity.User;  
  10. public class UserDaoImpl implements UserDao {  
  11.     private SessionFactory sessionFactory;  
  12.       
  13.     public void setSessionFactory(SessionFactory sessionFactory) {  
  14.         this.sessionFactory = sessionFactory;  
  15.     }  
  16.   
  17.     @Override  
  18.     public void addUser(User user) {  
  19.         sessionFactory.getCurrentSession().save(user);  
  20.     }  
  21.   
  22.     @Override  
  23.     public boolean deleteUser(String id) {  
  24.         String hql = "delete from User where id=?";  
  25.         Query query = sessionFactory.getCurrentSession().createQuery(hql);  
  26.         query.setString(0, id);  
  27.         return query.executeUpdate()>0;  
  28.     }  
  29.   
  30.     @Override  
  31.     public List<User> getAll() {  
  32.         String hql = "from User";  
  33.         Query query = sessionFactory.getCurrentSession().createQuery(hql);  
  34.         return query.list();  
  35.     }  
  36.   
  37.     @Override  
  38.     public User getUser(String id) {  
  39.         String hql = "from User where id=?";  
  40.         Query query = sessionFactory.getCurrentSession().createQuery(hql);  
  41.         query.setString(0, id);  
  42.         return (User) query.uniqueResult();  
  43.     }  
  44.   
  45.     @Override  
  46.     public boolean modifyUser(User user) {  
  47.         String hql = "update User set name=?,age=? where id=?";  
  48.         Query query = sessionFactory.getCurrentSession().createQuery(hql);  
  49.         query.setString(0, user.getName());  
  50.         query.setInteger(1, user.getAge());  
  51.         query.setString(2, user.getId());  
  52.         return query.executeUpdate()>0;  
  53.     }  
  54.   
  55. }  

UserService.java

  1. package com.xdy.service;  
  2.   
  3.   
  4. import java.util.List;  
  5.   
  6. import com.xdy.entity.User;  
  7.   
  8. public interface UserService {  
  9.   
  10.     public void addUser(User user);  
  11.       
  12.     public List<User> getAll();  
  13.       
  14.     public boolean deleteUser(String id);  
  15.       
  16.     public User getUser(String id);  
  17.       
  18.     public boolean modifyUser(User user);  
  19. }  
UserServiceImpl.java

  1. package com.xdy.service.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.xdy.dao.UserDao;  
  6. import com.xdy.entity.User;  
  7. import com.xdy.service.UserService;  
  8.   
  9. public class UserServiceImpl implements UserService {  
  10.     private UserDao userDao;  
  11.   
  12.     public void setUserDao(UserDao userDao) {  
  13.         this.userDao = userDao;  
  14.     }  
  15.   
  16.     @Override  
  17.     public void addUser(User user) {  
  18.         userDao.addUser(user);  
  19.     }  
  20.   
  21.     @Override  
  22.     public List<User> getAll() {  
  23.         return userDao.getAll();  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean deleteUser(String id) {  
  28.         return userDao.deleteUser(id);  
  29.     }  
  30.   
  31.     @Override  
  32.     public User getUser(String id) {  
  33.         return userDao.getUser(id);  
  34.     }  
  35.   
  36.     @Override  
  37.     public boolean modifyUser(User user) {  
  38.         return userDao.modifyUser(user);  
  39.     }  
  40.   
  41. }  
UserController.java

  1. package com.xdy.controller;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.annotation.Resource;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13.   
  14. import com.xdy.entity.User;  
  15. import com.xdy.service.UserService;  
  16.   
  17. @Controller  
  18. @RequestMapping("/user")  
  19. public class UserController {  
  20.     @Resource(name="userService")  
  21.     private UserService userService;  
  22.       
  23.     @RequestMapping("/addUser")  
  24.     public String addUser(User user){  
  25.         userService.addUser(user);  
  26.         return "redirect:/user/getAll";  
  27.     }  
  28.       
  29.     @RequestMapping("/toAddUser")  
  30.     public String toAddUser(){  
  31.         return "/addUser";  
  32.     }  
  33.       
  34.     @RequestMapping("/getAll")  
  35.     public String getAll(HttpServletRequest request){  
  36.         List<User> users = userService.getAll();  
  37.         request.setAttribute("users", users);  
  38.         return "/userList";  
  39.     }  
  40.       
  41.     @RequestMapping("/deleteUser")  
  42.     public void deleteUser(String id,HttpServletResponse response){  
  43.         String result = "{\"result\":\"error\"}";  
  44.         if(userService.deleteUser(id)){  
  45.             result = "{\"result\":\"success\"}";  
  46.         }  
  47.         response.setContentType("application/json");  
  48.         try {  
  49.             PrintWriter out = response.getWriter();  
  50.             out.write(result);  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.     }  
  55.       
  56.     @RequestMapping("/getUser")  
  57.     public String getUser(String id,HttpServletRequest request){  
  58.         User user = userService.getUser(id);  
  59.         request.setAttribute("user", user);  
  60.         return "/editUser";  
  61.     }  
  62.       
  63.     @RequestMapping("/modifyUser")  
  64.     public String modifyUser(User user){  
  65.         if(userService.modifyUser(user)){  
  66.             return "redirect:/user/getAll";  
  67.         }else{  
  68.             return "/error";  
  69.         }  
  70.     }  
  71.   
  72. }  
springMVC+spring+hibernate增删改查实例

4、前端页面

addUser.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>添加用户</title>  
  7.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  8.     <meta http-equiv="description" content="This is my page">  
  9.   </head>  
  10.   <body>  
  11.     <form action="/springMvc11/user/addUser" method="post">  
  12.         用户名:<input type="text" name="name"><br/>  
  13.         年龄:<input type="text" name="age"><br/>  
  14.         <input type="submit" value="添加用户">  
  15.     </form>  
  16.   </body>  
  17. </html>  
editUser.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>修改用户</title>  
  7.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  8.     <meta http-equiv="description" content="This is my page">  
  9.   </head>  
  10.   <body>  
  11.     <form action="/springMvc11/user/modifyUser" method="post">  
  12.         <input type="hidden" name="id" value="${user.id }">  
  13.         用户名:<input type="text" name="name" value="${user.name }"><br/>  
  14.         年龄:<input type="text" name="age" value="${user.age }"><br/>  
  15.         <input type="submit" value="修改">  
  16.     </form>  
  17.   </body>  
  18. </html>  
userList.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>用户列表</title>  
  7.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  8.     <meta http-equiv="description" content="This is my page">  
  9.     <script type="text/javascript" src="../js/jquery-1.4.3.js"></script>  
  10.     <script type="text/javascript">  
  11.         function deleteUser(id){  
  12.             $.get("/springMvc11/user/deleteUser?id=" + id,function(data){  
  13.                 if("success" == data.result){  
  14.                     alert("删除成功!");  
  15.                     window.location.reload();   
  16.                 }else{  
  17.                     alert("删除失败!")  
  18.                 }  
  19.             });  
  20.         }  
  21.   
  22.     </script>  
  23.       
  24.   </head>  
  25.   <body>  
  26.         <table border="1">  
  27.             <tbody>  
  28.                 <tr>  
  29.                     <th>名字</th>  
  30.                     <th>年龄</th>  
  31.                     <th>操作</th>  
  32.                 </tr>  
  33.                     <c:forEach items="${users}" var="u">  
  34.                         <tr>  
  35.                             <td>${u.name }</td>  
  36.                             <td>${u.age }</td>  
  37.                             <td>  
  38.                                 <a href="/springMvc11/user/getUser?id=${u.id }">更新</a>  
  39.                                 <a href="javascript:deleteUser('${u.id }');">删除</a>  
  40.                             </td>  
  41.                         </tr>  
  42.                     </c:forEach>  
  43.             </tbody>  
  44.         </table>  
  45.   </body>  
  46. </html>