SpringBoot HelloWorld 之 实现注册功能

本文来自:IT宝库(https://www.itbaoku.cn)

SpringBoot HelloWorld 之 实现注册功能

一.配置

image-20240531234226339

创建数据库big_event

CREATE TABLE `user` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',`username` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT '用户名',`password` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '密码',`nickname` varchar(10) COLLATE utf8_unicode_ci DEFAULT '' COMMENT '昵称',`email` varchar(128) COLLATE utf8_unicode_ci DEFAULT '' COMMENT '邮箱',`user_pic` varchar(128) COLLATE utf8_unicode_ci DEFAULT '' COMMENT '头像',`create_time` datetime NOT NULL COMMENT '创建时间',`update_time` datetime NOT NULL COMMENT '修改时间',PRIMARY KEY (`id`),UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='用户表'

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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.javalearn</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>demo</description><properties><java.version>17</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>3.0.2</spring-boot.version></properties><dependencies><!-- MySQL Driver --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
<!--&lt;!&ndash;        persistence&ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>javax.persistence</groupId>-->
<!--            <artifactId>persistence-api</artifactId>-->
<!--            <version>1.0</version>-->
<!--        </dependency>-->
<!--jdbc--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- Spring Boot Starter Data JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--        mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.0</version></dependency>
<!--        -->
<!--        -->
<!--        --><!--mybatis依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.0</version></dependency><!--mysql驱动依赖--><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId></dependency><!--lombok依赖--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--validation依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><!--java-jwt坐标--><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version></dependency><!--单元测试的坐标--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!--pageHelper坐标--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.6</version></dependency><!--阿里云oss依赖坐标--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version></dependency>
<!--        -->
<!--        -->
<!--        --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>17</source><target>17</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version><configuration><mainClass>com.javalearn.demo.DemoApplication</mainClass><skip>true</skip></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>

src/main/resources/application.yml

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/big_eventusername: rootpassword: root
server:port: 8080mybatis:configuration:map-underscore-to-camel-case: true #开启驼峰命名和下划线命名的自动转换log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

二.controller控制层

src/main/java/com/javalearn/demo/controller/UserController.java

package com.javalearn.demo.controller;import com.javalearn.demo.pojo.Result;
import com.javalearn.demo.pojo.User;
import com.javalearn.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController { @Autowiredprivate UserService userService;@PostMapping("/register")public Result register(String username, String password) { // 查询用户User u = userService.findByUsername(username);if (u == null) { // 没有占用// 注册userService.register(username, password);return Result.success();} else { return Result.error("用户名已占用");}}}

三.service业务层

src/main/java/com/javalearn/demo/service/UserService.java

package com.javalearn.demo.service;import com.javalearn.demo.pojo.User;
import java.util.List;public interface UserService { // 根据用户名查询User findByUsername(String username);// 注册void register(String username, String password);}

src/main/java/com/javalearn/demo/service/impl/UserServiceImpl.java

package com.javalearn.demo.service.impl;import com.javalearn.demo.pojo.User;
import com.javalearn.demo.mapper.UserMapper;
import com.javalearn.demo.service.UserService;
import com.javalearn.demo.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl implements UserService { @Autowiredprivate UserMapper userMapper;@Overridepublic User findByUsername(String username) { User u = userMapper.findByUsername(username);return u;}@Overridepublic void register(String username, String password){ // 加密String md5String = Md5Util.getMD5String(password);// 添加userMapper.add(username, md5String);}
}

四.mapper(Dao)持久层

src/main/java/com/javalearn/demo/mapper/UserMapper.java

package com.javalearn.demo.mapper;import com.javalearn.demo.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;@Mapper
public interface UserMapper { // 根据用户名查询用户@Select("select * from user where username = #{username}")User findByUsername(String username);// 添加@Insert("insert into user(username, password, create_time, update_time)" +" values(#{username}, #{password},now(),now())")void add(@Param("username") String uasername, @Param("password") String password);
}

五.pojo(简单java对象)

src/main/java/com/javalearn/demo/pojo/Result.java

package com.javalearn.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;//统一响应结果
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Result<T> { private Integer code;//业务状态码  0-成功  1-失败private String message;//提示信息private T data;//响应数据//快速返回操作成功响应结果(带响应数据)public static <E> Result<E> success(E data) { return new Result<>(0, "操作成功", data);}//快速返回操作成功响应结果public static Result success() { return new Result(0, "操作成功", null);}public static Result error(String message) { return new Result(1, message, null);}
}

src/main/java/com/javalearn/demo/pojo/User.java

package com.javalearn.demo.pojo;import lombok.Data;
import java.time.LocalDateTime;@Data
public class User { private Integer id;//主键IDprivate String username;private String password;private String nickname;//昵称private String email;private String userPic;//用户头像地址private String createTime;private String updateTime;
}

六.utils(工具)

src/main/java/com/javalearn/demo/utils/Md5Util.java

package com.javalearn.demo.utils;import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class Md5Util { /*** 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合*/protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};protected static MessageDigest messagedigest = null;static { try { messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException nsaex) { System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");nsaex.printStackTrace();}}/*** 生成字符串的md5校验值** @param s* @return*/public static String getMD5String(String s) { return getMD5String(s.getBytes());}/*** 判断字符串的md5校验码是否与一个已知的md5码相匹配** @param password  要校验的字符串* @param md5PwdStr 已知的md5校验码* @return*/public static boolean checkPassword(String password, String md5PwdStr) { String s = getMD5String(password);return s.equals(md5PwdStr);}public static String getMD5String(byte[] bytes) { messagedigest.update(bytes);return bufferToHex(messagedigest.digest());}private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length);}private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n);int k = m + n;for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer);}return stringbuffer.toString();}private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换stringbuffer.append(c0);stringbuffer.append(c1);}}

image-20240601000005429

image-20240601000022636