基于SpringMVC的数据库的增、删、改、查
感想
在昨天配置好Maven和SMM环境的基础下,今天终于可以开始写真正的逻辑代码了。这次的需求主要是写好一个简单的数据库的增删改查。虽然在之前已经用不同语言写过了无数次的数据库操作,但是这次却不一样了,我们需要按照SpringMVC框架来编写相关操作,所以在编写这次的程序之前,我通过询问老师和查询相关网络资源了解了SPringMVC基本的调用和执行过程。虽然如此,在编写程序的时候还是遇到了许多问题,从一开始的404到后来的数据未注入,种种情况都遇到了。但是最终还是依靠和队友讨论以及求助大佬完成了此次的任务。
以下是这次的代码:
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.读取数据库配置文件properties的属性:${url} -->
<context:property-placeholder location="classpath:properties/db.properties"/>
<!-- 2.配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描bean包 使用别名 -->
<property name="typeAliasesPackage" value="com.zzj.people_manage.entity"/>
<!--配置加载映射文件 UserMapper.xml,很容易写错-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--配置mybatis配置文件位置-->
<!-- <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>-->
</bean>
<!-- 自动生成dao,mapper-->
<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包,这里很容易写错 -->
<property name="basePackage" value="com.zzj.people_manage.dao"/>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--自动扫描-->
<!-- <context:component-scan base-package="com.zzj.people_manage"/>-->
<context:component-scan base-package="com.zzj.people_manage.dao"/>
<context:component-scan base-package="com.zzj.people_manage.service"/>
<!-- 配置事务-->
<!-- 5.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 6.开启事务注解-->
<tx:annotation-driven/>
</beans>
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.注解扫描位置-->
<context:component-scan base-package="com.zzj.people_manage.controller" />
<!-- 2.配置映射处理和适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 3.视图的解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
UserController
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private IUserDao userDao;
@RequestMapping("/all")
public String all(Model model) {
List<User> users=userDao.getUsers();
//键值对形式添加进model
model.addAttribute("users", users);
return "index";
}
@RequestMapping("/toAddUser")
public String toAddUser(User user){
return "addUser";
}
@RequestMapping("/addUser")
public String addUser(User user) {
userDao.addUser(user);
return "redirect:/user/all";
}
@RequestMapping("/toChangeName")
public String toChangeName(Model model, Integer id){
model.addAttribute("user",userDao.getUserById(id));
return "changeName";
}
@RequestMapping("/changeName")
public String changeName(Model model, User user){
userDao.changeName(user);
System.out.println(user);
user = userDao.getUserById(user.id);
model.addAttribute("user", user);
return "redirect:/user/all";
}
}
IUserDao
public interface IUserDao {
List<User> getUsers();
int addUser(User user);
User getUserById(Integer id);
int changeName(User user);
}
User(实体类)
public class User {
public Integer id;
public String name;
public String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
UserMapper.xml(数据库映射)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zzj.people_manage.dao.IUserDao">
<resultMap type="User" id="userResultMap" >
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</resultMap>
<select id="getUsers" resultType="User">
select * from tb_user
</select>
<insert id="addUser" parameterType="User">
INSERT INTO tb_user(id,name,sex) VALUE (#{id},#{name},#{sex})
</insert>
<select id="getUserById" resultType="User" parameterType="Integer">
SELECT id,name,sex
FROM tb_user
WHERE id=#{id}
</select>
<update id="changeName" parameterType="User">
UPDATE tb_user
SET NAME = #{name}
WHERE id = #{id}
</update>
</mapper>
Index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>武理表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h2 align="center">武汉理工大学学生信息表</h2>
<h2 align="center"><a href="${path }/user/toAddUser">点击进入新增用户界面</a></h2>
<table class="table table-hover table-striped" >
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="item" items="${users}">
<tr>
<td>${item.name}</td>
<td>${item.sex}</td>
<td>
<a href="${path }/user/toChangeName?id=${item.id}">修改${item.name}姓名</a> |
<a href="${path }/user/toChangeSex?id=${itemm.id}">修改${item.name}性别</a> |
<a href="${path }/user/deleteUser?id=${item.id}">删除${item.name}</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
changeName.jsp
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>改名</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h2 align="center">修改无理人姓名</h2>
<form action="" name="userForm">
<input type="hidden" name="id" value="${user.id}"/>
<div align="center">
<br><br>输入修改后的姓名:<input type="text" name="name" value="${user.name}"/>
<input type="button" value="提交" onclick="changeName()"/>
</div>
</form>
<script type="text/javascript">
function changeName() {
var form = document.forms[0];
form.action = "<%=basePath %>user/changeName";
form.method = "post";
form.submit();
}
</script>
</body>
</html>