秒杀项目之登录
目录
一、技术点介绍
前端:Freemarker、LayUI、jQuery
后端:SpringBoot、MyBatisPlus、Lombok
中间件:RabbitMQ、Redis(redisson)
分布式协调框架:zookeeper
二、学习目标
1.安全优化:隐藏秒杀地址、验证码、接口限流
2.服务优化:RabbitMQ消息队列、接口优化、分布式锁
3.页面优化:缓存、静态化分离
4.分布式会话:用户登录、共享session
5.功能开发:商品列表、商品详情、秒杀、订单详情
6.系统压测:JMeter入门、自定义变量、压测
三、如何设计一个秒杀系统
秒杀,对我们来说,都不是一个陌生的东西。每年的双11,618以及时下流行的直播等等。
秒杀然而,这对于我们系统而言是一个巨大的考验。那么,如何才能更好地理解秒杀呢?我觉得作为一个程序员,你首先要从高维度出发,从整体上思考问题。
在我看来,秒杀其实主要解决两个问题,一个是并发读,一个是并发写。并发读的核心优化理念是尽量减少用户
到服务端来“读”数据,或者让他们读更少的数据;并发写的处理原则也一样,他要求我们在数据库层面独立出来
一个库,做特殊的处理。另外,我们还要针对秒杀系统做一个保护,针对意料之外的情况设计兜底方案,以防止最坏
的情况发生。其实,秒杀的整体架构可以概括为“稳、准、块”几个关键字
稳:整个系统架构要满足高可用,流量符合预期时肯定要稳定,就是超出预期时也同样不能掉链子,你
要保证秒杀活动顺利完成,即秒杀商品顺利地卖出去,这个是最基本的前提。
准:秒杀10台小米手机,那就只能成交10件,多一台少一台都不行。一旦库存不对,那平台就要承担损失,
所以准就是要求保证数据的一致性。
快:系统的性能足够高,否则你怎么支撑这么大的流量呢?不光是服务端要做极致的性能优化,而且在整个
请求链路上都要做协同的优化,每个地方快一点,整个系统就完美了。
★ 四、项目环境搭建
1、 创建SpringBoot项目并配置POM
2、导入对应的pom依赖
<?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.zxy</groupId>
<artifactId>seckill</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>seckill</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.4.1</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis plus依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--mybatis-plus生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<!-- MD5依赖 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- valid验证依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--hariki-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</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>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<mainClass>com.zxy.seckill.SeckillApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3、导入数据库及表

4、 配置application.yml
(1)添加数据库及连接池配置
(2)添加freemarker配置
(3)添加mybatis-plus配置
(4)添加logging日志配置
spring:
application:
name: seckill
datasource:
url: jdbc:mysql://localhost:3306/spa?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
hikari:
# 最小空闲连接数量
minimum-idle: 5
# 空闲连接存活最大时间,默认600000(10分钟)
idle-timeout: 180000
# 连接池最大连接数,默认是10
maximum-pool-size: 10
# 此属性控制从池返回的连接的默认自动提交行为,默认值:true
auto-commit: true
# 连接池名称
pool-name: MyHikariCP
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
max-lifetime: 1800000
# 数据库连接超时时间,默认30秒,即30000
connection-timeout: 30000
freemarker:
#设置编码格式
charset: UTF-8
#后缀
suffix: .ftl
#文档类型
content-type: text/html
#模板前端
template-loader-path: classpath:/templates/
#启用模板
enabled: true
#开启静态资源
mvc:
static-path-pattern: /static/**
mybatis-plus:
mapper-locations: classpath*:/mapper/*Mapper.xml
#要被访问到的类别名
type-aliases-package: com.zxy.seckill.model
configuration:
#能否使用驼峰命名
map-underscore-to-camel-case: true
#开启日志
logging:
level:
com.zxy.seckill.mapper: debug
5、启动类中添加注解
@SpringBootApplication
//打开切面
@EnableAspectJAutoProxy
//打开事务
@EnableTransactionManagement
@MapperScan("com.zxy.seckill.mapper")
6、使用Mybatis-plus反向生成代码
MybatisPlusGenerator:
package com.zxy.seckill.generator;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@SuppressWarnings("all")
@Slf4j
@Data
public class MybatisPlusGenerator {
protected static String URL = "jdbc:mysql://localhost/spa?useEncoding=utf8mb4&serverTimezone=Asia/Shanghai&useSSL=false";
protected static String USERNAME = "root";
protected static String PASSWORD = "123456";
protected static DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig.Builder(URL, USERNAME, PASSWORD);
public static void main(String[] args) {
FastAutoGenerator.create(DATA_SOURCE_CONFIG)
.globalConfig(
(scanner/*lamdba*/, builder/*变量*/) ->
builder.author(scanner.apply("请输入作者名称?"))
.enableSwagger()
.fileOverride()
.outputDir(System.getProperty("user.dir") + "\\src\\main\\java")
.commentDate("yyyy-MM-dd")
.dateType(DateType.TIME_PACK)
)
.packageConfig((builder) ->
builder.parent("com.zxy.seckill")
.entity("pojo")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.xml("mapper.xml")
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "\\src\\main\\resources\\mapper"))
)
.injectionConfig((builder) ->
builder.beforeOutputFile(
(a, b) -> log.warn("tableInfo: " + a.getEntityName())
)
)
.strategyConfig((scanner, builder) ->
builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.addTablePrefix("tb_", "t_")
.entityBuilder()
.enableChainModel()
.enableLombok()
.enableTableFieldAnnotation()
.addTableFills(
new Column("create_time", FieldFill.INSERT)
)
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.build())
.templateEngine(new FreemarkerTemplateEngine())
.execute();
}
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
}
生成完毕:
7、userMapper添加@Repository注解
package com.zxy.seckill.mapper;
import com.zxy.seckill.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* <p>
* 用户信息表 Mapper 接口
* </p>
*
* @author zxy
* @since 2022-03-15
*/
//不加此注解就不能加载到springbean里面去
@Repository
public interface UserMapper extends BaseMapper<User> {
}
五、前端构建
1、创建登录界面
head.ftl
<meta charset="UTF-8">
<title>秒杀项目</title>
<script src="/static/asset/js/layui/layui.js" type="text/javascript"></script>
<link href="/static/asset/js/layui/css/layui.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">
<#--自定义一个 ctx变量-->
<#assign ctx>
<#-- springboot在最初运行时的路径 -->
${springMacroRequestContext.getContextPath()}
</#assign>
goodslist. ftl
<!DOCTYPE html>
<html lang="en">
<head>
<#include "../common/head.ftl">
</head>
<body>
<h1>这是商品展示界面</h1>
</body>
</html>
login.ftl
<!DOCTYPE html>
<html lang="zh">
<head>
<#include "common/head.ftl"/>
<style>
.layui-panel {
position: absolute;
width: 400px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 15px 15px 0px 15px;
border-radius: 20px;
}
.layui-form-label {
padding: 9px 0px;
}
h3 {
text-align: center;
line-height: 45px;
font-size: 40px;
color: white;
padding-bottom: 15px;
}
</style>
</head>
<body>
<div>
<div class="layui-panel layui-bg-cyan">
<h3>用户登录</h3>
<div class="layui-form-item">
<label class="layui-form-label">用户账号</label>
<div class="layui-input-block">
<input type="text" id="mobile" autocomplete="on" class="layui-input" value="18684671234">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户密码</label>
<div class="layui-input-block">
<input type="password" id="password" autocomplete="on" class="layui-input" value="123456">
</div>
</div>
<div class="layui-form-item" style="text-align:center;">
<button class="layui-btn" id="login" style="width:46%">登录</button>
<button class="layui-btn layui-btn-normal" id="register" style="width:46%">注册</button>
</div>
</div>
</div>
<script src="${ctx}/static/asset/js/project/md5.js"></script>
<script src="${ctx}/static/asset/js/project/login.js"></script>
</body>
</html>
3、在js目录下新建目录project
新建JavaScript文件login:
layui.define(()=>{
// 得到layui中封装的jquery
let $=layui.jquery
// 给登录按钮设置事件
$(login).click(()=>{
// 取到表单的值
let mobile = $("#mobile").val();
let password=$("#password").val();
// 将数据给后台(前后端分离axios,普通开发ajax)
$.ajax({
url:"",//后台登录接口
data:{
// 需要携带的数据
mobile,
password
},
datatype: "json",//后端给你的数据类型
success(e){
// 成功的回调函数
},
error(e){
// 报错的回调函数
}
})
})
})
4、新建controller类
专门用于跳转路径:PathController类
package com.zxy.seckill.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class pathController {
@RequestMapping("/")
public String toPath(){
return "login";
}
@RequestMapping("/{dir}/{path}")
public String toPath(@PathVariable("dir") String dir,@PathVariable("path") String path){
return dir+"/"+path;
}
}
运行所得到界面:
六、MD5加密
1、导入帮助包与exception包
①、exception
package com.zxy.seckill.exception;
import com.zxy.seckill.util.response.ResponseResultCode;
import lombok.Data;
@SuppressWarnings("all")
@Data
public class BusinessException extends RuntimeException {
private ResponseResultCode responseResultCode;
public BusinessException(ResponseResultCode responseResultCode) {
this.responseResultCode = responseResultCode;
}
}
②、response包
JsonResponseParse :
package com.zxy.seckill.util.response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@SuppressWarnings("all")
@RestControllerAdvice
@Slf4j
public class JsonResponseParse implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
//返回值决定他是否需要进入beforeBodyWrite
return methodParameter.getMethod().isAnnotationPresent(JsonResponseResult.class);
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//更改返回值
if (o == null) {
return ResponseResult.success();
}
if (o instanceof Integer) {
return ResponseResult.failure(ResponseResultCode.queryCode((Integer) o));
}
if (o instanceof ResponseResultCode) {
return ResponseResult.failure((ResponseResultCode) o);
}
if (o instanceof ResponseResult) {
return o;
}
return ResponseResult.success(o);
}
}
JsonResponseResult :
package com.zxy.seckill.util.response;
import java.lang.annotation.*;
@SuppressWarnings("all")
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Target({ElementType.METHOD})
public @interface JsonResponseResult {
}
ResponseResult:
package com.zxy.seckill.util.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@SuppressWarnings("all")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> implements Serializable {
private int code;
private String message;
private T data;
private Long total;
/**
* 私有构造, 只允许通过static调用构造
*
* @param resultCode 结果枚举
* @param data 响应数据
*/
private ResponseResult(ResponseResultCode resultCode, T data) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.data = data;
}
/**
* 私有构造, 只允许通过static调用构造
*
* @param resultCode 结果枚举
* @param data 响应数据
*/
private ResponseResult(ResponseResultCode resultCode, Long total, T data) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.data = data;
this.total = total;
}
/**
* 成功调用返回的结果(无数据携带)
*/
public static ResponseResult success() {
return success(null);
}
/**
* 成功调用返回的结果(数据携带)
*
* @param data 携带的数据
*/
public static <T> ResponseResult success(T data) {
return new ResponseResult(ResponseResultCode.SUCCESS, data);
}
/**
* 成功调用返回的结果(分页使用)
*
* @param data 携带的数据
* @param total 数据总条数
*/
public static <T> ResponseResult success(T data, Long total) {
return new ResponseResult(ResponseResultCode.SUCCESS, total, data);
}
/**
* 失败调用返回的结果(数据携带)
*
* @param resultCode 状态枚举
* @param data 携带的数据
*/
public static <T> ResponseResult failure(ResponseResultCode resultCode, T data) {
return new ResponseResult(resultCode, data);
}
/**
* 失败调用返回的结果(无数据携带)
*
* @param resultCode 状态枚举
*/
public static ResponseResult failure(ResponseResultCode resultCode) {
return failure(resultCode, null);
}
}
ResponseResultCode :
package com.zxy.seckill.util.response;
import java.io.Serializable;
@SuppressWarnings("all")
public enum ResponseResultCode implements Serializable {
/* 正常状态 */
SUCCESS(200, "成功"),
FAILURE(300, "失败"),
UNKNOWN(400, "未知错误"),
/**
* 用户code范围: 1000;
*/
USER_ACCOUNT_NOT_FIND(1001, "用户名不存在"),
USER_ACCOUNT_DISABLED(1002, "该用户已被禁用"),
USER_PASSWORD_NOT_MATCH(1003, "该用户密码不一致"),
USER_PERMISSION_ERROR(1004, "该用户不具备访问权限"),
USER_STATE_OFF_LINE(1005, "该用户未登录"),
USER_CREDENTIAL_NOT_BE_EMPTY(1006, "用户的登录信息不能为空值"),
USER_ACCOUNT_NOT_MOBLIE(1007, "该用户登录信息格式不符合"),
USER_LOGIN_ERROR(1008, "登录失败"),
/**
* 其它异常: 4000;
*/
TICKET_ERROR(4001, "TICKET失效,请重新登录"),
/**
* 商品异常: 6000;
*/
GOODS_ADD_ERROR(6001, "商品添加失败"),
GOODS_EDIT_ERROR(6002, "商品修改失败"),
GOODS_REMOVE_ERROR(6003, "商品删除失败"),
/**
* 秒杀商品异常: 8000
*/
SECKILL_GOODS_ADD_ERROR(8001, "秒杀商品增加失败"),
/**
* 秒杀订单异常: 10000
*/
SECKILL_ORDER_ERROR(10001, "秒杀订单增加失败"),
SECKILL_ORDER_QUANTITY_ERROR(10002, "秒杀商品数量不足"),
SECKILL_ORDER_EXISTS_ERROR(10002, "秒杀订单已经存在"),
;
private final Integer code;
private final String message;
ResponseResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public static ResponseResultCode queryCode(Integer code) {
for (ResponseResultCode value : values()) {
if (code.equals(value.code)) {
return value;
}
}
return UNKNOWN;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
RestThrowableAdvice :
package com.zxy.seckill.util.response;
import com.zxy.seckill.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Arrays;
@SuppressWarnings("all")
@RestControllerAdvice
@Slf4j
public class RestThrowableAdvice {
@JsonResponseResult
@ExceptionHandler(value = {BusinessException.class})
public Object globalBusinessException(Model m, Exception e) {
log.error(e.toString());
return ((BusinessException) e).getResponseResultCode();
}
@JsonResponseResult
@ExceptionHandler(value = {BindException.class})
public Object globalBindException(Model m, Exception e) {
log.error(e.toString());
BindException error = (BindException) e;
return Arrays
.stream(error.getFieldError().getArguments())
.filter(arg -> arg instanceof ResponseResultCode)
.findAny()
.orElse(ResponseResultCode.UNKNOWN);
}
@JsonResponseResult
@ExceptionHandler(value = {Throwable.class})
public Object globalException(Model m, Exception e) {
log.error(e.toString());
return ResponseResultCode.UNKNOWN;
}
}
③、MD5Utils
package com.zxy.seckill.util;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import java.util.UUID;
/**
* MD5加密
* 用户端:password=MD5(明文+固定Salt)
* 服务端:password=MD5(用户输入+随机Salt)
* 用户端MD5加密是为了防止用户密码在网络中明文传输,服务端MD5加密是为了提高密码安全性,双重保险。
*/
@Component
@SuppressWarnings("all")
public class MD5Utils {
//加密盐,与前端一致
private static String salt = "f1g2h3j4";
/**
* md5加密
*
* @param src
* @return
*/
public static String md5(String src) {
return DigestUtils.md5Hex(src);
}
/**
* 获取加密的盐
*
* @return
*/
public static String createSalt() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 将前端的明文密码通过MD5加密方式加密成后端服务所需密码
* 注意:该步骤实际是在前端完成!!!
*
* @param inputPass 明文密码
* @return
*/
public static String inputPassToFormpass(String inputPass) {
//混淆固定盐salt,安全性更可靠
String str = salt.charAt(1) + "" + salt.charAt(5) + inputPass + salt.charAt(0) + "" + salt.charAt(3);
return md5(str);
}
/**
* 将后端密文密码+随机salt生成数据库的密码
*
* @param formPass
* @param salt
* @return
*/
public static String formPassToDbPass(String formPass, String salt) {
//混淆固定盐salt,安全性更可靠
String str = salt.charAt(7) + "" + salt.charAt(9) + formPass + salt.charAt(1) + "" + salt.charAt(5);
return md5(str);
}
/**
* 将用户输入的密码转换成数据库的密码
*
* @param inputPass 明文密码
* @param salt 盐
* @return
*/
public static String inputPassToDbPass(String inputPass, String salt) {
String formPass = inputPassToFormpass(inputPass);
String dbPass = formPassToDbPass(formPass, salt);
return dbPass;
}
public static void main(String[] args) {
String formPass = inputPassToFormpass("123456");
System.out.println("前端加密密码:" + formPass);
String salt = createSalt();
System.out.println("后端加密随机盐:" + salt);
String dbPass = formPassToDbPass(formPass, salt);
System.out.println("后端加密密码:" + dbPass);
String dbPass1 = inputPassToDbPass("123456", salt);
System.out.println("最终加密密码:" + dbPass1);
}
}
ValidatorUtils :
package com.zxy.seckill.util;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("all")
public class ValidatorUtils {
private static final Pattern mobile_pattern = Pattern.compile("[1]([0-9])[0-9]{9}$");
public static boolean isMobile(String mobile) {
if (StringUtils.isEmpty(mobile)) {
return false;
}
Matcher matcher = mobile_pattern.matcher(mobile);
return matcher.matches();
}
}
2、新建vo类
用于前后端传值:
package com.zxy.seckill.vo;
import lombok.Data;
@Data
public class UserVo {
// 手机号
private String mobine;
// 密码
private String password;
}
3、登录方法:
IUserService层:
package com.zxy.seckill.service;
import com.zxy.seckill.pojo.User;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zxy.seckill.util.response.ResponseResult;
import com.zxy.seckill.vo.UserVo;
/**
* <p>
* 用户信息表 服务类
* </p>
*
* @author zxy
* @since 2022-03-15
*/
public interface IUserService extends IService<User> {
ResponseResult<?> findByAccount(UserVo uservo);
}
UserServiceImpl类:
package com.zxy.seckill.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.seckill.pojo.User;
import com.zxy.seckill.mapper.UserMapper;
import com.zxy.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.seckill.util.ValidatorUtils;
import com.zxy.seckill.util.response.ResponseResult;
import com.zxy.seckill.util.response.ResponseResultCode;
import com.zxy.seckill.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
* <p>
* 用户信息表 服务实现类
* </p>
*
* @author zxy
* @since 2022-03-15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Override
public ResponseResult<?> findByAccount(UserVo userVo) {
// 先判断信息是否符合(账号是否是手机号码,密码是不是空)
// .getMobine()拿到手机号
if(!ValidatorUtils.isMobile(userVo.getMobine())){
return ResponseResult.failure(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE);
}
if(!StringUtils.isBlank(userVo.getPassword())){
return ResponseResult.failure(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
}
// 再去数据库查出对应的用户(mobile)
User user=this.getOne(new QueryWrapper<User>().eq("id",userVo.getMobine()));
if(user==null){
return ResponseResult.failure(ResponseResultCode.USER_ACCOUNT_NOT_FIND);
}
// 比较密码
if(userVo.getPassword().equals(user.getPassword())){
return ResponseResult.failure(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
}
return ResponseResult.success();
}
}
UserController类:
package com.zxy.seckill.controller;
import com.zxy.seckill.service.IUserService;
import com.zxy.seckill.util.response.ResponseResult;
import com.zxy.seckill.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 用户信息表 前端控制器
* </p>
*
* @author zxy
* @since 2022-03-15
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
// 用户登录
@RequestMapping("/login")
public ResponseResult<?> login(UserVo userVo){
// 调用service的登录验证
return userService.findByAccount(userVo);
}
}
得到密钥,登录成功:
七、 全局异常抓获
1、给实体类userVo加入注解
package com.zxy.seckill.vo;
import com.zxy.seckill.util.response.ResponseResultCode;
import com.zxy.seckill.util.validate.IsMobile;
import com.zxy.seckill.util.validate.IsRequired;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class UserVo {
// 手机号
@IsMobile(code = ResponseResultCode.USER_ACCOUNT_NOT_FIND)
private String mobile;
// 密码
@IsRequired(code = ResponseResultCode.USER_CREDENTIAL_NOT_BE_EMPTY)
private String password;
}
2、导入帮助包validate,异常抓获
IsMobile:
package com.zxy.seckill.util.validate;
import com.zxy.seckill.util.response.ResponseResultCode;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@SuppressWarnings("all")
@Documented
@Constraint(
validatedBy = {IsMobileValidator.class}
)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsMobile {
ResponseResultCode code() default ResponseResultCode.UNKNOWN;
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
IsMobileValidator:
package com.zxy.seckill.util.validate;
import com.zxy.seckill.util.ValidatorUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@SuppressWarnings("all")
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
@Override
public boolean isValid(String mobile, ConstraintValidatorContext context) {
return ValidatorUtils.isMobile(mobile);
}
}
IsRequired:
package com.zxy.seckill.util.validate;
import com.zxy.seckill.util.response.ResponseResultCode;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@SuppressWarnings("all")
@Documented
@Constraint(
validatedBy = {IsRequiredValidator.class}
)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsRequired {
ResponseResultCode code() default ResponseResultCode.UNKNOWN;
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
IsRequiredValidator:
package com.zxy.seckill.util.validate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@SuppressWarnings("all")
@Slf4j
public class IsRequiredValidator implements ConstraintValidator<IsRequired, String> {
@Override
public boolean isValid(String str, ConstraintValidatorContext context) {
return StringUtils.isNotBlank(str);
}
}
ThrowableAdvice:
package com.zxy.seckill.util.response;
import com.zxy.seckill.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@SuppressWarnings("all")
@RestControllerAdvice
@Slf4j
public class ThrowableAdvice {
@JsonResponseResult
@ExceptionHandler(value = {BusinessException.class})
public ResponseResultCode globalBusinessException(Model m, Exception e) {
log.error(e.toString());
return ((BusinessException) e).getResponseResultCode();
}
@JsonResponseResult
@ExceptionHandler(value = {BindException.class})
public ResponseResultCode globalBindException(Model m, Exception e) {
log.error(e.toString());
BindException error = (BindException) e;
return (ResponseResultCode) error.getFieldError().getArguments()[1];
}
@JsonResponseResult
@ExceptionHandler(value = {Throwable.class})
public ResponseResultCode globalException(Model m, Exception e) {
log.error(e.toString());
return ResponseResultCode.UNKNOWN;
}
}
3、在UserController类方法中加入注解
开启jsr303验证
@Valid
4、实现类抛出异常
package com.zxy.seckill.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.zxy.seckill.exception.BusinessException; import com.zxy.seckill.pojo.User; import com.zxy.seckill.mapper.UserMapper; import com.zxy.seckill.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zxy.seckill.util.MD5Utils; import com.zxy.seckill.util.ValidatorUtils; import com.zxy.seckill.util.response.ResponseResult; import com.zxy.seckill.util.response.ResponseResultCode; import com.zxy.seckill.vo.UserVo; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import java.util.Date; /** * <p> * 用户信息表 服务实现类 * </p> * * @author zxy * @since 2022-03-15 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Override public ResponseResult<?> findByAccount(UserVo userVo) { // 先判断信息是否符合(账号是否是手机号码,密码是不是空) if(!ValidatorUtils.isMobile(userVo.getMobile())){ throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE); } if(StringUtils.isBlank(userVo.getPassword())){ throw new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH); } // 再去数据库查出对应的用户(mobile) User user=this.getOne(new QueryWrapper<User>().eq("id",userVo.getMobile())); if(user==null){ throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_FIND); } // 比较密码 // 二重加密(前端->后端,后端->数据库) String salt=user.getSalt(); // 将前台的加密密码和后端的盐再次进行加密 String newPassword=MD5Utils.formPassToDbPass(userVo.getPassword(),salt); if(!newPassword.equals(user.getPassword())){ throw new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH); } // 修改最后的登录时间 this.update(new UpdateWrapper<User>().eq("id",userVo.getMobile()).set("last_login_date",new Date()).setSql("login_count=login_count+1")); return ResponseResult.success(); } }
密码错误时不会报错: