springMVC(14) springMVC+spring+hibernate增删改查实例

时间:2022-02-02 05:48:57

1、导包

springMVC(14) springMVC+spring+hibernate增删改查实例

springMVC(14) springMVC+spring+hibernate增删改查实例

2、配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>

<!-- 配置spring启动listener入口 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 配置springMVC启动DispatcherServlete入口 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-annotation.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>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</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>

spring-annotation.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.xdy" />
<mvc:annotation-driven />

<!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**" />
<mvc:resources location="/js/" mapping="/js/**" />

<!-- 配置解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 支持上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
</beans>

spring-hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.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/springmvc"></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 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="annotatedClasses">
<list>
<value>com.xdy.entity.User</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" lazy-init="true"
abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_NEVER</prop>
</props>
</property>
</bean>

</beans>

spring-core.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 导入spring配置 -->
<import
resource="classpath*:com/xdy/spring/springAnnotation-import.xml" />
</beans>

springAnnotation-import.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.xdy" />
<mvc:annotation-driven />

<!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**" />
<mvc:resources location="/js/" mapping="/js/**" />

<!-- 配置解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 支持上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
</beans>

3、后台代码

User.java

package com.xdy.entity;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
@Column(length=32)
private String id;

@Column(length=32)
private String name;

@Column(length=32)
private Integer age;

public String getId() {
return id;
}

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

public String getName() {
return name;
}

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

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}

UserDao.java

package com.xdy.dao;

import java.util.List;


import com.xdy.entity.User;

public interface UserDao {

public void addUser(User user);

public boolean deleteUser(String id);

public boolean modifyUser(User user);

public List<User> getAll();

public User getUser(String id);
}

UserDaoImpl.java

package com.xdy.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.xdy.dao.UserDao;
import com.xdy.entity.User;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;

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

@Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}

@Override
public boolean deleteUser(String id) {
String hql = "delete from User where id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return query.executeUpdate()>0;
}

@Override
public List<User> getAll() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}

@Override
public User getUser(String id) {
String hql = "from User where id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (User) query.uniqueResult();
}

@Override
public boolean modifyUser(User user) {
String hql = "update User set name=?,age=? where id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, user.getName());
query.setInteger(1, user.getAge());
query.setString(2, user.getId());
return query.executeUpdate()>0;
}

}

UserService.java

package com.xdy.service;


import java.util.List;

import com.xdy.entity.User;

public interface UserService {

public void addUser(User user);

public List<User> getAll();

public boolean deleteUser(String id);

public User getUser(String id);

public boolean modifyUser(User user);
}

UserServiceImpl.java

package com.xdy.service.impl;

import java.util.List;

import com.xdy.dao.UserDao;
import com.xdy.entity.User;
import com.xdy.service.UserService;

public class UserServiceImpl implements UserService {
private UserDao userDao;

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

@Override
public void addUser(User user) {
userDao.addUser(user);
}

@Override
public List<User> getAll() {
return userDao.getAll();
}

@Override
public boolean deleteUser(String id) {
return userDao.deleteUser(id);
}

@Override
public User getUser(String id) {
return userDao.getUser(id);
}

@Override
public boolean modifyUser(User user) {
return userDao.modifyUser(user);
}

}

UserController.java

package com.xdy.controller;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xdy.entity.User;
import com.xdy.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
@Resource(name="userService")
private UserService userService;

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

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

@RequestMapping("/getAll")
public String getAll(HttpServletRequest request){
List<User> users = userService.getAll();
request.setAttribute("users", users);
return "/userList";
}

@RequestMapping("/deleteUser")
public void deleteUser(String id,HttpServletResponse response){
String result = "{\"result\":\"error\"}";
if(userService.deleteUser(id)){
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");
try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}

@RequestMapping("/getUser")
public String getUser(String id,HttpServletRequest request){
User user = userService.getUser(id);
request.setAttribute("user", user);
return "/editUser";
}

@RequestMapping("/modifyUser")
public String modifyUser(User user){
if(userService.modifyUser(user)){
return "redirect:/user/getAll";
}else{
return "/error";
}
}

}

4、前端页面

addUser.jsp

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

editUser.jsp

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

userList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户列表</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="../js/jquery-1.4.3.js"></script>
<script type="text/javascript">
function deleteUser(id){
$.get("/springMvc11/user/deleteUser?id=" + id,function(data){
if("success" == data.result){
alert("删除成功!");
window.location.reload();
}else{
alert("删除失败!")
}
});
}

</script>

</head>
<body>
<table border="1">
<tbody>
<tr>
<th>名字</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="u">
<tr>
<td>${u.name }</td>
<td>${u.age }</td>
<td>
<a href="/springMvc11/user/getUser?id=${u.id }">更新</a>
<a href="javascript:deleteUser('${u.id }');">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>