1.本次项目基于maven管理项目,采用SpringMVC框架,使用c3p0数据连接池以及MySQL数据库进行项目。
1.1创建数据库:
create database if not exists springdemo;
1.2创建Account用户表
create table if not exists Account(id int(4) auto_increment primary key,name varchar(16) not null,password varchar(16) not null,age int(3) ,createtime datetime default now(),money int(8));
2.项目的创建:
首先创建一个maven工程:
对项目的Tomcat进行配置:
3.在pom.xml中引入项目的依赖文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springMvc_CRUD_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>springMvc_CRUD_demo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<!-- 配置项目的编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 配置项目的jdk的版本-->
<maven.compiler.source>1.8</maven.compiler.source>
<!-- 配置jdk编译器的版本-->
<maven.compiler.target>1.8</maven.compiler.target>
<!-- spring的版本,方便下文引用-->
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 引入Spring的context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--引入Spring的web依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入Spring的MVC依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入Spring用于访问数据库的JDBC依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入数据源c3p0依赖-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- 引入MySQL数据库依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--引入servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--引入jsp的API依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 引入Spring解析JSon数据的依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
</dependencies>
<build>
<finalName>springMvc_CRUD_demo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
4.开始编写项目的实体类,业务逻辑类。
package daomain;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.util.Date;
/**
* Classname:Account
*
* @description:
* @author: 陌意随影
* @Date: 2020-08-05 23:06
* @Version: 1.0
**/
@Repository("account")
@Scope("prototype")
public class Account implements Serializable {
//用户的唯一主键ID
private int id;
//用户名
private String name;
//用户密码
private String password;
//用户年龄
private int age;
//用户创建时间
private Date createTime;
//用户的钱
private int money;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
public Date getCreateTime() {
return createTime;
}
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
", createTime=" + createTime +
", money=" + money +
'}';
}
}
package dao;
import daomain.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Classname:springMvc_response_demo
*
* @description:{description}
* @author: 陌意随影
* @Date: 2020-08-07 00:00
*/
public interface AccountDao {
/**
* @Description :保存用户
* @Date 21:10 2020/8/7 0007
* @Param * @param account :
* @return boolean
**/
public boolean save(Account account);
/**
* @Description :通过ID删除用户
* @Date 21:10 2020/8/7 0007
* @Param * @param id :
* @return boolean
**/
public boolean delteAccount(int id);
//跟新用户
public boolean updateAccount(Account newAccount);
//通过ID查找用户
public Account findAccount(int id);
//查找所有用户
public List<Account> findAllAccount();
}
package dao.impl;
import dao.AccountDao;
import daomain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Classname:AccountDaoImpl
*
* @description:
* @author: 陌意随影
* @Date: 2020-08-07 00:05
* @Version: 1.0
**/
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplete ;
@Override
public boolean save(Account account) {
return jdbcTemplete.update("insert into account(name,password,age,createTime,money) values(?,?,?,?,?)",account.getName(),
account.getPassword(),account.getAge(),account.getCreateTime(),account.getMoney()) == 1;
}
@Override
public boolean delteAccount(int id) {
return jdbcTemplete.update("delete from account where id=?",id) == 1;
}
@Override
public boolean updateAccount(Account newAccount) {
return jdbcTemplete.update("update account set name=?,password=?,age=?,createTime=?,money=? where id=?",newAccount.getName(),newAccount.getPassword(),newAccount.getAge(),
newAccount.getCreateTime(),newAccount.getMoney(),newAccount.getId())== 1;
}
@Override
public Account findAccount(int id) {
List<Account> accountList = jdbcTemplete.query("select* from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), id);
if (accountList.isEmpty()){
return null;
}
if (accountList.size() == 1){
return accountList.get(0);
}
return null;
}
@Override
public List<Account> findAllAccount() {
return jdbcTemplete.query("select* from account ",new BeanPropertyRowMapper<Account>(Account.class));
}
}
package service;
import daomain.Account;
import java.util.List;
/**
* Classname:springMvc_response_demo
*
* @description:{description}
* @author: 陌意随影
* @Date: 2020-08-07 00:02
*/
public interface AccountService {
/**
* @Description :保存用户
* @Date 21:10 2020/8/7 0007
* @Param * @param account :
* @return boolean
**/
public boolean save(Account account);
/**
* @Description :通过ID删除用户
* @Date 21:10 2020/8/7 0007
* @Param * @param id :
* @return boolean
**/
public boolean delteAccount(int id);
//跟新用户
public boolean updateAccount(Account newAccount);
//通过ID查找用户
public Account findAccount(int id);
//查找所有用户
public List<Account> findAllAccount();
}
package service.impl;
import dao.AccountDao;
import daomain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.AccountService;
import java.util.List;
/**
* Classname:AccountServiceImpl
*
* @description:
* @author: 陌意随影
* @Date: 2020-08-07 00:03
* @Version: 1.0
**/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public boolean save(Account account) {
return accountDao.save(account);
}
@Override
public boolean delteAccount(int id) {
return accountDao.delteAccount(id);
}
@Override
public boolean updateAccount(Account newAccount) {
return accountDao.updateAccount(newAccount);
}
@Override
public Account findAccount(int id) {
return accountDao.findAccount(id);
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
}
5.书写控制器的代码
package controller;
import daomain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import service.AccountService;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
* Classname:AccountController
*
* @description:
* @author: 陌意随影
* @Date: 2020-08-05 23:07
* @Version: 1.0
**/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService ;
/**
* @Description :保存用户
* @Date 21:15 2020/8/7 0007
* @Param * @param account :
* @return java.lang.String
**/
@RequestMapping("/saveAccount")
public @ResponseBody String saveAccount(@RequestBody Account account){
boolean fla = accountService.save(account);
String str ="";
if (fla){
str ="{\"msg\":\"保存用户成功\"}";
System.out.println("保存用户:"+account);
}else{
str ="{\"msg\":\"保存用户失败\"}";
}
return str;
}
/**
* @Description :删除用户
* @Date 21:15 2020/8/7 0007
* @Param * @param id :
* @return java.lang.String
**/
@RequestMapping("/deleteAccount")
public @ResponseBody String deleteAccount(@RequestParam int id){
boolean fla = accountService.delteAccount(id);
String str ="";
if (fla){
str ="{\"msg\":\"删除用户成功\"}";
}else{
str ="{\"msg\":\"删除用户失败\"}";
}
return str;
}
/**
* @Description :更新用户
* @Date 21:16 2020/8/7 0007
* @Param * @param newAccount :
* @return java.lang.String
**/
@RequestMapping("/updateAccount")
public @ResponseBody String updateAccount(@RequestBody Account newAccount){
boolean fla = accountService.updateAccount(newAccount);
String str ="";
if (fla){
str ="{\"msg\":\"更新用户成功\"}";
}else{
str ="{\"msg\":\"更新用户失败\"}";
}
return str;
}
/**
* @Description :通过ID查找用户
* @Date 21:16 2020/8/7 0007
* @Param * @param id :
* @return java.lang.String
**/
@RequestMapping("/findAccountById")
public @ResponseBody String findAccountById(@RequestParam int id){
Account account = accountService.findAccount(id);
String str ="";
if (account != null){
str ="{\"msg\":\"查找用户成功\"}";
System.out.println("查找用户"+account);
}else{
str ="{\"msg\":\"查找用户失败\"}";
}
return str;
}
/**
* @Description :查找所有的用户
* @Date 21:16 2020/8/7 0007
* @Param * @param :
* @return java.lang.String
**/
@RequestMapping("/findAll")
public @ResponseBody String findAll(){
List<Account> accountList = accountService.findAllAccount();
String str ="";
if (accountList != null){
str ="{\"msg\":\"查找所有用户成功\"}";
System.out.println("查找所有用户:"+accountList);
}else{
str ="{\"msg\":\"查找所有用户失败\"}";
}
return str;
}
}
注意:
5.1.@RequestMapping(“/account”)表示将AccountController映射为一级目录/account,@RequestMapping(“/saveAccount”)表示将方法saveAccount(@RequestBody Account account)映射为二级目录
/account/saveAccount,当我们访问该方法时:account/saveAccount即为在前端的访问路径。
5.2.saveAccount(@RequestBody Account account)中的@RequestBody会将前端请求的JSon数据封装到Account对象中。在封装的过程中,需要用到
JSon的解析工具jackson-databind和jackson-core,所以在pom.xml中要引入对应的依赖。
并且在自动封装的过程中,由于实体类中有Java类型Date的属性createTime,而在json的数据中时间类型格式是不一样的,所以需要我们对实体类Account中Date类型进行处理。比如我在前端请求的数据为:
'{"id":"3","name":"root","password":"root","age":14,"createTime":"2020-08-01 10:39:39","money":54}'
理论上说自动封装后的实体类Account中的createTIme应该能疯转上的,但是事实上是在这个过程中发生了转换错误:
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2020-08-01 10:39:39": not a valid representation (error: Failed to parse Date value '2020-08-01 10:39:39': Cannot parse date "2020-08-01 10:39:39": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2020-08-01 10:39:39": not a valid representation (error: Failed to parse Date value '2020-08-01 10:39:39': Cannot parse date "2020-08-01 10:39:39": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
at [Source: (PushbackInputStream); line: 1, column: 56] (through reference chain: daomain.Account["createTime"])]
因此我们需要手动对其,处理的方式为使用JsonFormat注解:
5.3 public @ResponseBody String saveAccount(@RequestBody Account account)中 @ResponseBody注解会将返回值自动化为响应类型的格式,比如响应的类型是JSON,则自动转换为json格式。
5.4 public @ResponseBody String deleteAccount(@RequestParam int id)中的@RequestParam会将前端请求参数中的key为id的对应的value复制给参数id。比如 url:“account/findAccountById?id=6”,那么public @ResponseBody String deleteAccount(@RequestParam int id)中的参数id的值会自动获取为id=6.请求l参数中的key要和方法参数中的名称一致。
6.配置springMVCConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描每个包下的所有类-->
<context:component-scan base-package="controller"></context:component-scan>
<context:component-scan base-package="daomain"></context:component-scan>
<context:component-scan base-package="service"></context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
!-- 视图解析器对像这里表示解析 /WEB-INF/pages/下的jsp文件,此次演示并没有使用到pages这个文件夹,
这里配置好是为了使整个项目更加完善,想要增加前端页面可以在 /WEB-INF/pages/下添加新的jsp文件-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置JdbcTemplate,并注入数据源-->
<bean id="jdbcTemplete" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourecs"></property>
</bean>
<!-- 配置c3po数据源-->
<bean id="dataSourecs" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置数据库连接的用户名-->
<property name="user" value="root"></property>
<!-- 配置数据库连接的密码-->
<property name="password" value="root"></property>
<!-- 配置数据库连接的驱动-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<!-- 配置数据库连接的url-->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springdemo?serverTimezone=UTC"></property>
</bean>
<!-- 开启SpringMVC注解支持-->
<mvc:annotation-driven ></mvc:annotation-driven>
<!-- 放行静态资源
location表示要放行的文件
mapping表示放行文件的映射路径
mapping="/js/**" 表示放行js目录下的所有文件以及子文件夹中的文件
-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
</beans>
7…配置web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置前端控制器,对前端请求进行拦截-->
<servlet>
<servlet-name> dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 在启动时开始加载项目资源文件夹resources中的springMVCConfig.xml-->
<init-param>
<!-- 加载资源根目录文件-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVCConfig.xml</param-value>
</init-param>
<!-- 项目启动时开始加载文件-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 对所有的请求进行拦截-->
<servlet-mapping>
<servlet-name>dispatcherServlet</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>
</web-app>
8.在index.jsp中书写前端代码
<%--
Created by IntelliJ IDEA.
User: 陌意随影
Date: 2020/8/5 0005
Time: 23:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.2.1.min.js"></script>
<%-- <script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>--%>
<script>
$(function () {
//处理保存用户的ajax请求
$("#saveBtn").click(function () {
$.ajax({
url:"account/saveAccount",
contentType:"application/json;charset=UTF-8",
data:'{"name":"root","password":"root","age":14,"createTime":"2020-08-01 10:39:39","money":54}',
dataType:"json",
type:"post",
success:function (data) {
alert(data.msg)
}
})
});
//通过ID删除用户的ajax请求
$("#deleteBtn").click(function () {
$.ajax({
url:"account/deleteAccount?id=4",
dataType:"json",
type:"get",
success:function (data) {
alert(data.msg)
}
})
})
//通过id查找用户的ajax请求
$("#findByIdBtn").click(function () {
$.ajax({
url:"account/findAccountById?id=6",
dataType:"json",
type:"get",
success:function (data) {
alert(data.msg)
}
})
})
//查找全部用户的ajax请求
$("#findAllBtn").click(function () {
$.ajax({
url:"account/findAll",
dataType:"json",
type:"get",
success:function (data) {
alert(data.msg)
}
})
})
//处理更新用户的ajax请求
$("#updateBtn").click(function () {
$.ajax({
url:"account/updateAccount",
contentType:"application/json;charset=UTF-8",
data:'{"id":"3","name":"root","password":"root","age":14,"createTime":"2020-08-01 10:39:39","money":54}',
dataType:"json",
type:"post",
success:function (data) {
alert(data.msg)
}
})
});
})
</script>
</head>
<body>
<h3>首页</h3>
<button type="button" id="saveBtn">保存用户</button><br>
<button type="button" id="deleteBtn">删除用户</button><br>
<button type="button" id="findByIdBtn">根据ID获取用户</button><br>
<button type="button" id="findAllBtn">查询所有用户</button><br>
<button type="button" id="updateBtn">更新用户</button><br>
</body>
</html>
8.1注意:此次使用ajax发送异步请求,需要引入JQuery,
然后为了防止前端控制器拦截了静态资源文件,所以我们要在springMVCConfig.xml中放行资源文件不进行拦截。
8.2:测试时可以对每个ajax中的url参数进行修改,从而进行不同的增删查改操作。
8.3ajax请求数据data中的createTime格式要和 @JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)中的pattern格式一致。比如
当pattern=“yyyy-MM-dd HH:mm:ss”时, data:’{“id”:“3”,“name”:“root”,“password”:“root”,“age”:14,“createTime”:“2020-08-01 10:39:39”,“money”:54}’中的”createTime”:“2020-08-01 10:39:39”;
当pattern=“yyyy/MM/dd HH:mm:ss”时, data:’{“id”:“3”,“name”:“root”,“password”:“root”,“age”:14,“createTime”:“2020-08-01 10:39:39”,“money”:54}’中的”createTime”:“2020/08/01 10:39:39”,
9.开始启动Tomcat进行测试。
10.本项目的源代码已经上传到个人博客的服务器,有需要请访问该博客并下拉到文章底部: