1、首先要创建一个Spring boot 项目

这边我使用的是IntelliJ IDEA,我们先创建一个新项目

点击Project后,选择Spring Initializr

!!!这边我们要注意的是所选择的SDK,选择你所下载的SDK版本,后点击Next

这边需要注意的是Type中我们选择使用Maven,该工具可以帮助对项目进行一些快捷操作,下面的Java Version 要注意选择的是自己上一步所使用的JDK版本,后点击Next

在选择组件中我们可能需要使用到的就是网页端Spring web 以及数据库的Mybaits Framework and MySQL Driver,后面的Driver主要看你所使用什么数据库,这边我使用的是MySQL的数据库,所以选用该组件,然后就可以进行下一步Next操作了。

选择自己存放的位置后,点击Finish就创建好项目了.

创建完成后的项目文件为上图所示,这边需要注意到的是reasources文件夹中的application.project文件显示的为临时文件,可能是所使用的Spring boot版本不匹配,这边需要到下方pom.xml文件中进行修改

这边也可以看见默认使用的是java17的SDK我们需要修改成我们所使用的SDK,下方是修改后的代码。

4.0.0org.springframework.bootspring-boot-starter-parent2.7.6 com.exampledemo0.0.1-SNAPSHOTdemoDemo project for Spring Boot11org.springframework.bootspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.2.0com.mysqlmysql-connector-jruntimeorg.springframework.bootspring-boot-starter-testtestorg.mybatis.spring.bootmybatis-spring-boot-starter-test3.0.2testorg.springframework.bootspring-boot-maven-plugin

接下来我们创建一个数据库,这边我们创建一个注册的用户名单

create schema test;use test;create table t_user1(uid int auto_increment comment '用户id',username varchar(20) not null unique comment '用户名',password char(32) not null comment '密码',salt char(36) comment '盐值',phone varchar(20) comment '电话号码',email varchar(30) comment '电子邮箱',gender int comment '性别女——0,男——1',avatar varchar(50) comment '头像',is_delete int comment '是否删除:0——未删除,1——已删除',created_user varchar(20) comment '日志-创建人',created_time datetime comment '日志-创建时间',modified_user varchar(20) comment '日志-最后修改执行人',modified_time datetime comment '日志-最后修改时间',primary key(uid))engine=InnoDB default charset=utf8;

由此一个数据库表便建成了,接下来我们需要对项目与数据库进行连接,点击进入application.project文件进行配置

server.port=8080spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456

其中server.port=8080,为在网页访问该项目的端口号,若不设置的话,默认为8080,接下来我们点击项目左上方开始按钮进行运行

显示该项目启动成功端口号为8080,后面我们需要对填入数据库的对象进行抽象方法的编写

我们在demo文件夹下创建一个user的文件夹后再创建一个User的java类

import java.io.Serializable;import java.util.Date;public class User implements Serializable {private String createdUser;private Date createdTime;private String modifiedUser;private Date modifiedTime;private Integer uid;private String username;private String password;private String salt;private String phone;private String email;private Integer gender;private String avatar;private Integer isDelete;public String getCreatedUser() {return createdUser;}public void setCreatedUser(String createdUser) {this.createdUser = createdUser;}public Date getCreatedTime() {return createdTime;}public void setCreatedTime(Date createdTime) {this.createdTime = createdTime;}public String getModifiedUser() {return modifiedUser;}public void setModifiedUser(String modifiedUser) {this.modifiedUser = modifiedUser;}public Date getModifiedTime() {return modifiedTime;}public void setModifiedTime(Date modifiedTime) {this.modifiedTime = modifiedTime;}public Integer getUid() {return uid;}public void setUid(Integer uid) {this.uid = uid;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getSalt() {return salt;}public void setSalt(String salt) {this.salt = salt;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public String getAvatar() {return avatar;}public void setAvatar(String avatar) {this.avatar = avatar;}public Integer getIsDelete() {return isDelete;}public void setIsDelete(Integer isDelete) {this.isDelete = isDelete;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (!(o instanceof User)) return false;User user = (User) o;if (getCreatedUser() != null " />

上面是对数据库中所创建的对象进行抽象方法的编写,接下来我们要编写一个接口,来进行对数据库的插入,

仍是在demo文件夹下创建一个mapper文件夹并再创建一个名为UserMapper的接口文件

import com.example.demo.user.User;public interface UserMapper {Integer insert(User user);}

下面我们就需要编写对数据库插入的映射文件,mybaits的编写,在reasources中创建一个与mapper文件夹一样的名字和xml文件

INSERT INTOt_user(username,password,salt,phone,email,gender,avatar,is_delete,created_user,created_time,modified_user,modified_time)VALUES(#{username},#{password},#{salt},#{phone},#{email},#{gender},#{avatar},#{isDelete},#{createdUser},#{createdTime},#{modifiedUser},#{modifiedTime})

而后我们需要在DemoApplication中编写mapper的文件位置

import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.example.demo.mapper")public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}

接下来我们需要开始编写对数据库插入时可能出现的异常编写,方便我们再出错的时候更快速的定位到问题所在处,编写服务层的代码,我们需要在demo文件夹下创建两个文件夹,分别是ex和impl

首先我们在ex文件夹中编写所可能出现的异常情况,可能出现的异常有服务超时以及我们所插入的数据有异常,因此我们需要写两个异常处理,在ex文件夹中创建InsertExpection 和 ServiceExpection这两个java类,

ServiceExpection的代码如下:

public class ServiceExpection extends RuntimeException {public ServiceExpection() {super();}public ServiceExpection(String message) {super(message);}public ServiceExpection(String message, Throwable cause) {super(message, cause);}public ServiceExpection(Throwable cause) {super(cause);}protected ServiceExpection(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}}

Insertexpection的代码如下:

public class InsertException extends ServiceExpection {public InsertException() {super();}public InsertException(String message) {super(message);}public InsertException(String message, Throwable cause) {super(message, cause);}public InsertException(Throwable cause) {super(cause);}protected InsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}}

接下来我们需要编写应用层的接口来实现对数据的处理,在impl文件夹中创建UserService和serServiceImpl这两个Java类

UserService的代码如下:

import com.example.demo.user.User;public interface UserService {void reg(User user);}

UserServiceImpl的代码如下:

import com.example.demo.ex.InsertException;import com.example.demo.mapper.UserMapper;import com.example.demo.user.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.util.DigestUtils;import java.io.Serializable;import java.util.Date;import java.util.UUID;@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic void reg(User user){Date date = new Date();String oldPassword = user.getPassword();if(oldPassword == null){throw new InsertException("未输入密码");}String salt = UUID.randomUUID().toString().toUpperCase();String MD5Password = getMD5Oassword(oldPassword,salt);user.setPassword(MD5Password);user.setUsername(user.getUsername());user.setSalt(salt);user.setCreatedTime(date);user.setModifiedTime(date);user.setCreatedUser(user.getUsername());user.setModifiedUser(user.getUsername());Integer rows = userMapper.insert(user);if(rows != 1){throw new InsertException("插入未知异常");}}private String getMD5Oassword(String password,String salt){for(int i =0;i<3;i++){password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();}return password;}}

其中在UserServiceImpl类中自动适配不能定义UserMapper为userMapper这边并不影响编译内容需要更改级别在file中打开到Setting找到Autowiring for Bean Class将其等级调味警告即可

接下来我们要编写数据传输的格式,这边我们统一将数据以Json的格式进行传送,在demo文件夹下创建一个名为format的文件夹,在其下创建一个JsonResult的Java类

JsonResult的代码如下:

import java.io.Serializable;public class JsonResult implements Serializable {private Integer state;private String message;private E data;public JsonResult() {}public JsonResult(Integer state, E data) {this.state = state;this.data = data;}public JsonResult(Integer state, String message, E data) {this.state = state;this.message = message;this.data = data;}public Integer getState() {return state;}public void setState(Integer state) {this.state = state;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public E getData() {return data;}public void setData(E data) {this.data = data;}}

后面就是最后一步了,我们需要给定一个访问的url让后端可以接受网页传输的数据,我们在demo下创建一个Control的文件夹,在其下在创建一个UserControl的java类

UserControld的代码如下:

import com.example.demo.ex.InsertException;import com.example.demo.format.JsonResult;import com.example.demo.impl.UserService;import com.example.demo.user.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("users")public class UserControl {@Autowiredprivate UserService userService;@RequestMapping("reg")public JsonResult reg(User user){JsonResult result = new JsonResult();try{userService.reg(user);result.setState(200);result.setMessage("插入成功");}catch(InsertException e){result.setState(5000);result.setMessage("插入异常");}return result;}}

而后我们运行项目,当看到服务器启动成功后,打卡浏览器输入http://localhost:8080/users/reg?username=test&password=111回车

便可以看见插入成功了,打卡数据库中也可以看见该条数据

这边只完成了插入的功能,若后面有查询等类似的整体的框架都差不多,只需将相对应的代码做一些修改即可。