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,下方是修改后的代码。
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
接下来我们创建一个数据库,这边我们创建一个注册的用户名单
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=8080
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (getCreatedUser() != null ? !getCreatedUser().equals(user.getCreatedUser()) : user.getCreatedUser() != null)
return false;
if (getCreatedTime() != null ? !getCreatedTime().equals(user.getCreatedTime()) : user.getCreatedTime() != null)
return false;
if (getModifiedUser() != null ? !getModifiedUser().equals(user.getModifiedUser()) : user.getModifiedUser() != null)
return false;
if (getModifiedTime() != null ? !getModifiedTime().equals(user.getModifiedTime()) : user.getModifiedTime() != null)
return false;
if (getUid() != null ? !getUid().equals(user.getUid()) : user.getUid() != null) return false;
if (getUsername() != null ? !getUsername().equals(user.getUsername()) : user.getUsername() != null)
return false;
if (getPassword() != null ? !getPassword().equals(user.getPassword()) : user.getPassword() != null)
return false;
if (getSalt() != null ? !getSalt().equals(user.getSalt()) : user.getSalt() != null) return false;
if (getPhone() != null ? !getPhone().equals(user.getPhone()) : user.getPhone() != null) return false;
if (getEmail() != null ? !getEmail().equals(user.getEmail()) : user.getEmail() != null) return false;
if (getGender() != null ? !getGender().equals(user.getGender()) : user.getGender() != null) return false;
if (getAvatar() != null ? !getAvatar().equals(user.getAvatar()) : user.getAvatar() != null) return false;
return getIsDelete() != null ? getIsDelete().equals(user.getIsDelete()) : user.getIsDelete() == null;
}
@Override
public int hashCode() {
int result = getCreatedUser() != null ? getCreatedUser().hashCode() : 0;
result = 31 * result + (getCreatedTime() != null ? getCreatedTime().hashCode() : 0);
result = 31 * result + (getModifiedUser() != null ? getModifiedUser().hashCode() : 0);
result = 31 * result + (getModifiedTime() != null ? getModifiedTime().hashCode() : 0);
result = 31 * result + (getUid() != null ? getUid().hashCode() : 0);
result = 31 * result + (getUsername() != null ? getUsername().hashCode() : 0);
result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0);
result = 31 * result + (getSalt() != null ? getSalt().hashCode() : 0);
result = 31 * result + (getPhone() != null ? getPhone().hashCode() : 0);
result = 31 * result + (getEmail() != null ? getEmail().hashCode() : 0);
result = 31 * result + (getGender() != null ? getGender().hashCode() : 0);
result = 31 * result + (getAvatar() != null ? getAvatar().hashCode() : 0);
result = 31 * result + (getIsDelete() != null ? getIsDelete().hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"createdUser='" + createdUser + '\'' +
", createdTime=" + createdTime +
", modifiedUser='" + modifiedUser + '\'' +
", modifiedTime=" + modifiedTime +
", uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", avatar='" + avatar + '\'' +
", isDelete=" + isDelete +
'}';
}
}
上面是对数据库中所创建的对象进行抽象方法的编写,接下来我们要编写一个接口,来进行对数据库的插入,
仍是在demo文件夹下创建一个mapper文件夹并再创建一个名为UserMapper的接口文件
import com.example.demo.user.User;
public interface UserMapper {
Integer insert(User user);
}
下面我们就需要编写对数据库插入的映射文件,mybaits的编写,在reasources中创建一个与mapper文件夹一样的名字和xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sr.store.mapper.UserMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="uid">
INSERT INTO
t_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}
)
</insert>
而后我们需要在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;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public 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<E> 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 {
@Autowired
private UserService userService;
@RequestMapping("reg")
public JsonResult<Void> reg(User user){
JsonResult<Void> 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回车
便可以看见插入成功了,打卡数据库中也可以看见该条数据
这边只完成了插入的功能,若后面有查询等类似的整体的框架都差不多,只需将相对应的代码做一些修改即可。