IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 秒杀项目前期之登录功能 -> 正文阅读

[大数据]秒杀项目前期之登录功能

目录

一、秒杀技术点介绍

二、秒杀学习目标

三、如何设计一个秒杀系统

四、项目环境搭建

? ? ? ? 1、配置数据库及表

? ? ? ? 2、创建SpringBoot项目并配置POM

? ? ? ? 3、配置application.yml

? ? ? ? 4、使用Mybatis-plus反向生成代码

? ? ? ? 5、用户登陆

? ? ? ? ? ? ? ? ?1、后端搭建:

? ? ? ? ? ? ? ? ?2、前端搭建:

? ? ? ? 6、进行测试

五、双重加密(盐加密,MD5加密)

1、先导入exception类

2、新建一个UserVo类,用于前后端传值

3、导入MD5.js文件

4、前端--->后端进行加密?

5、后端--->数据库进行加密?

六、Js303验证(全局异常)

1、先导入全局异常类?

2、加载四个类,关于UserVo中的属性类

3、在UserVo中的属性上加入注解

4、进行测试


一、秒杀技术点介绍

前端:Freemarker、LayUI、jQuery
后端:SpringBoot、MyBatisPlus、Lombok
中间件:RabbitMQ、Redis(redisson)
分布式协调框架:zookeeper

二、秒杀学习目标

1.安全优化:隐藏秒杀地址、验证码、接口限流
2.服务优化:RabbitMQ消息队列、接口优化、分布式锁
3.页面优化:缓存、静态化分离
4.分布式会话:用户登录、共享session
5.功能开发:商品列表、商品详情、秒杀、订单详情
6.系统压测:JMeter入门、自定义变量、压测

三、如何设计一个秒杀系统

总的来说:稳准快

秒杀,对我们来说,都不是一个陌生的东西。每年的双11,618以及时下流行的直播等等。
秒杀然而,这对于我们系统而言是一个巨大的考验。

那么,如何才能更好地理解秒杀呢?我觉得作为一个程序员,你首先要从高维度出发,从整体上思考问题。
在我看来,秒杀其实主要解决两个问题,
一个是并发读,一个是并发写。
并发读的核心优化理念是尽量减少用户
到服务端来“读”数据,或者让他们读更少的数据;并发写的处理原则也一样,他要求我们在数据库层面独立出来
一个库,做特殊的处理。另外,我们还要针对秒杀系统做一个保护,针对意料之外的情况设计兜底方案,以防止最坏
的情况发生。

其实,秒杀的整体架构可以概括为“稳、准、快”几个关键字
稳:整个系统架构要满足高可用,流量符合预期时肯定要稳定,就是超出预期时也同样不能掉链子,你
要保证秒杀活动顺利完成,即秒杀商品顺利地卖出去,这个是最基本的前提。
准:秒杀10台小米手机,那就只能成交10件,多一台少一台都不行。一旦库存不对,那平台就要承担损失,
所以准就是要求保证数据的一致性。
快:系统的性能足够高,否则你怎么支撑这么大的流量呢?不光是服务端要做极致的性能优化,而且在整个
请求链路上都要做协同的优化,每个地方快一点,整个系统就完美了。

四、项目环境搭建

? ? ? ? 1、配置数据库及表

运行sql脚本,构建数据库,其中里面有五张表,用户表、订单表、商品表、秒杀订单表、秒杀商品表

? ? ? ? 2、创建SpringBoot项目并配置POM

pom依赖:?

pom依赖中包含了如下依赖:

?spring-boot-starter-freemarker
? ? ? spring-boot-starter-web
? ? ? mysql-connector-java 5.1.44
? ? ? lombok
? ? ? <!-- mybatis plus依赖 -->
? ? ? mybatis-plus-boot-starter 3.4.0
? ? ? mybatis-plus-generator 3.4.0
? ? ? <!-- hariki连接池 -->
? ? ? HikariCP
? ? ? <!-- MD5依赖 -->
? ? ? commons-codec
? ? ? commons-lang3 3.6
? ? ? <!-- valid验证依赖 -->
? ? ? spring-boot-starter-validation
? ? ? <!-- redis -->
? ? ? spring-boot-starter-data-redis

<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>

? ? ? ? 3、配置application.yml

如下代码加红的是要注意的

? ? ? 1)添加数据库及连接池配置
? ? ? 2)添加freemarker配置
? ? ? 3)添加mybatis-plus配置
? ? ? 4)添加logging日志配置

spring:
  application:
    name: SecKill
  datasource:
    url: jdbc:mysql://localhost:3306/secKill?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: password
    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.zj.seckill.pojo
  configuration:
    map-underscore-to-camel-case: true
logging:
  level:
    com.zj.seckill.mapper: debug

? ? ? ? 4、使用Mybatis-plus反向生成代码

编码一个genetator类:

MybatisPlusGenerator:
package com.zj.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:3306/secKill?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF8";
    protected static String USERNAME = "root";
    protected static String PASSWORD = "password";

    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.zj.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(","));
    }

}

运行此类就会生成对应的文件:

?有几个要注意的地方

1、UserMapper一定要打@Repository注解

2、在启动类一定要打以下注解?

@SpringBootApplication
@MapperScan("com.zj.seckill.mapper")
@EnableAspectJAutoProxy
@EnableTransactionManagement

? ? ? ? 5、用户登陆

? ? ? ? ? ? ? ? ?1、后端搭建:

IUserService:
package com.zj.seckill.service;

import com.zj.seckill.pojo.User;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zj.seckill.util.response.ResponseResult;
import com.zj.seckill.vo.UserVo;

/**
 * <p>
 * 用户信息表 服务类
 * </p>
 *
 * @author zj
 * @since 2022-03-15
 */
public interface IUserService extends IService<User> {

    ResponseResult<?> findByAccount(UserVo userVo);
}
UserServiceImpl:
package com.zj.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zj.seckill.exception.BusinessException;
import com.zj.seckill.pojo.User;
import com.zj.seckill.pojo.mapper.UserMapper;
import com.zj.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zj.seckill.util.MD5Utils;
import com.zj.seckill.util.ValidatorUtils;
import com.zj.seckill.util.response.ResponseResult;
import com.zj.seckill.util.response.ResponseResultCode;
import com.zj.seckill.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zj
 * @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())) {
//            return ResponseResult.failure(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE);
        throw  new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE);
        }
        if (StringUtils.isBlank(userVo.getPassword())) {
//            return ResponseResult.failure(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
            throw  new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH);


        }
        //再去数据库中查出对应的用户
        User user = this.getOne(new QueryWrapper<User>().eq("id", userVo.getMobile()));
        if (user == null) {
//            return ResponseResult.failure(ResponseResultCode.USER_ACCOUNT_NOT_FIND);
            throw  new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_FIND);
        }
        //再比较密码
        //二重加密(前端--->后端 后端--->数据库)
        String salt = user.getSalt();
        String newpassword = MD5Utils.formPassToDbPass(userVo.getPassword(), salt);
        System.out.println(newpassword+"----"+user.getPassword());
        if (!newpassword.equals(user.getPassword())) {
//            return ResponseResult.failure(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
            throw  new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
        }
        return ResponseResult.success();
    }
}

UserController:

package com.zj.seckill.controller;

import com.zj.seckill.service.IUserService;
import com.zj.seckill.util.response.ResponseResult;
import com.zj.seckill.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author zj
 * @since 2022-03-15
 */
@RestController
@RequestMapping("/user")
public class UserController {



    @Autowired
    private IUserService userService;



    @RequestMapping("/login")
    public ResponseResult<?> login(@Valid UserVo userVo){
        //调用service的登录验证
        return userService.findByAccount(userVo);


    }

}

? ? ? ? ? ? ? ? ?2、前端搭建:

1、导入layui

路径放在

<script src="${ctx}/static/asset/js/md5.js"></script>
<script src="${ctx}/static/asset/js/project/login.js"></script>

2、新建一个login.js在src/main/resources/static/asset/js/project

login.js:

layui.define(() => {
        //得到layui中封装的juery
        let $ = layui.jquery
        var layer = layui.layer
        //给登录的按钮设置事件
        $(login).click(() => {
            //取到表單的值
            let mobile = $("#mobile").val()
            let password = $("#password").val()
            //将数据给后台(前后台分离axios,普通开发ajax)
            let salt = "f1g2h3j4";
            //将密码和盐放在一起
            if (password) {
                password = salt.charAt(1) + "" + salt.charAt(5) + password + salt.charAt(0) + "" + salt.charAt(3);
                //进行md5加密
                password = md5(password);
            }
            console.log(password)
            //将数据给后台(前后台分离axios,普通开发ajax)
            $.ajax({
                url: "/user/login",
                data: {
                    mobile,
                    password
                },
                dataType: "json",
                success(e) {
                    layer.msg(e.message,{icon:6})
                },
                error(e) {
                }
            })
        })
    }
)

3、导入模板:

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">
<#assign ctx>
    ${springMacroRequestContext.getContextPath()}
</#assign>

?good.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/md5.js"></script>
<script src="${ctx}/static/asset/js/project/login.js"></script>
</body>
</html>

? ? ? ? 6、进行测试

后端打印结果:

测试成功,后端打印的是输入密码后左边双重加密后的结果,右边是数据库的密码

五、双重加密(盐加密,MD5加密)

双重加密的规则是从前端到后端加一次密,然后后端到数据库加一次密

1、先导入exception类

package com.zj.seckill.exception;

import com.zj.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;
    }

}

2、新建一个UserVo类,用于前后端传值

package com.zj.seckill.vo;


import com.zj.seckill.util.response.ResponseResultCode;
import com.zj.seckill.util.validate.IsMobile;
import com.zj.seckill.util.validate.IsRequired;
import lombok.Data;
import org.aspectj.apache.bcel.classfile.Code;

import javax.validation.constraints.NotEmpty;

@Data
public class UserVo {
    //自定义js303注解
    @IsMobile(code = ResponseResultCode.USER_ACCOUNT_NOT_FIND)
    private String mobile;

    @IsRequired(code = ResponseResultCode.USER_PASSWORD_NOT_MATCH)
    private String password;
}

3、导入MD5.js文件

/*
 * JavaScript MD5
 * https://github.com/blueimp/JavaScript-MD5
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 *
 * Based on
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/* global define */

(function ($) {
    'use strict'

    /*
    * Add integers, wrapping at 2^32. This uses 16-bit operations internally
    * to work around bugs in some JS interpreters.
    */
    function safeAdd (x, y) {
        var lsw = (x & 0xffff) + (y & 0xffff)
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
        return (msw << 16) | (lsw & 0xffff)
    }

    /*
    * Bitwise rotate a 32-bit number to the left.
    */
    function bitRotateLeft (num, cnt) {
        return (num << cnt) | (num >>> (32 - cnt))
    }

    /*
    * These functions implement the four basic operations the algorithm uses.
    */
    function md5cmn (q, a, b, x, s, t) {
        return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b)
    }
    function md5ff (a, b, c, d, x, s, t) {
        return md5cmn((b & c) | (~b & d), a, b, x, s, t)
    }
    function md5gg (a, b, c, d, x, s, t) {
        return md5cmn((b & d) | (c & ~d), a, b, x, s, t)
    }
    function md5hh (a, b, c, d, x, s, t) {
        return md5cmn(b ^ c ^ d, a, b, x, s, t)
    }
    function md5ii (a, b, c, d, x, s, t) {
        return md5cmn(c ^ (b | ~d), a, b, x, s, t)
    }

    /*
    * Calculate the MD5 of an array of little-endian words, and a bit length.
    */
    function binlMD5 (x, len) {
        /* append padding */
        x[len >> 5] |= 0x80 << (len % 32)
        x[((len + 64) >>> 9 << 4) + 14] = len

        var i
        var olda
        var oldb
        var oldc
        var oldd
        var a = 1732584193
        var b = -271733879
        var c = -1732584194
        var d = 271733878

        for (i = 0; i < x.length; i += 16) {
            olda = a
            oldb = b
            oldc = c
            oldd = d

            a = md5ff(a, b, c, d, x[i], 7, -680876936)
            d = md5ff(d, a, b, c, x[i + 1], 12, -389564586)
            c = md5ff(c, d, a, b, x[i + 2], 17, 606105819)
            b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330)
            a = md5ff(a, b, c, d, x[i + 4], 7, -176418897)
            d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426)
            c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341)
            b = md5ff(b, c, d, a, x[i + 7], 22, -45705983)
            a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416)
            d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417)
            c = md5ff(c, d, a, b, x[i + 10], 17, -42063)
            b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162)
            a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682)
            d = md5ff(d, a, b, c, x[i + 13], 12, -40341101)
            c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290)
            b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329)

            a = md5gg(a, b, c, d, x[i + 1], 5, -165796510)
            d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632)
            c = md5gg(c, d, a, b, x[i + 11], 14, 643717713)
            b = md5gg(b, c, d, a, x[i], 20, -373897302)
            a = md5gg(a, b, c, d, x[i + 5], 5, -701558691)
            d = md5gg(d, a, b, c, x[i + 10], 9, 38016083)
            c = md5gg(c, d, a, b, x[i + 15], 14, -660478335)
            b = md5gg(b, c, d, a, x[i + 4], 20, -405537848)
            a = md5gg(a, b, c, d, x[i + 9], 5, 568446438)
            d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690)
            c = md5gg(c, d, a, b, x[i + 3], 14, -187363961)
            b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501)
            a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467)
            d = md5gg(d, a, b, c, x[i + 2], 9, -51403784)
            c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473)
            b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734)

            a = md5hh(a, b, c, d, x[i + 5], 4, -378558)
            d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463)
            c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562)
            b = md5hh(b, c, d, a, x[i + 14], 23, -35309556)
            a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060)
            d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353)
            c = md5hh(c, d, a, b, x[i + 7], 16, -155497632)
            b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640)
            a = md5hh(a, b, c, d, x[i + 13], 4, 681279174)
            d = md5hh(d, a, b, c, x[i], 11, -358537222)
            c = md5hh(c, d, a, b, x[i + 3], 16, -722521979)
            b = md5hh(b, c, d, a, x[i + 6], 23, 76029189)
            a = md5hh(a, b, c, d, x[i + 9], 4, -640364487)
            d = md5hh(d, a, b, c, x[i + 12], 11, -421815835)
            c = md5hh(c, d, a, b, x[i + 15], 16, 530742520)
            b = md5hh(b, c, d, a, x[i + 2], 23, -995338651)

            a = md5ii(a, b, c, d, x[i], 6, -198630844)
            d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415)
            c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905)
            b = md5ii(b, c, d, a, x[i + 5], 21, -57434055)
            a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571)
            d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606)
            c = md5ii(c, d, a, b, x[i + 10], 15, -1051523)
            b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799)
            a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359)
            d = md5ii(d, a, b, c, x[i + 15], 10, -30611744)
            c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380)
            b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649)
            a = md5ii(a, b, c, d, x[i + 4], 6, -145523070)
            d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379)
            c = md5ii(c, d, a, b, x[i + 2], 15, 718787259)
            b = md5ii(b, c, d, a, x[i + 9], 21, -343485551)

            a = safeAdd(a, olda)
            b = safeAdd(b, oldb)
            c = safeAdd(c, oldc)
            d = safeAdd(d, oldd)
        }
        return [a, b, c, d]
    }

    /*
    * Convert an array of little-endian words to a string
    */
    function binl2rstr (input) {
        var i
        var output = ''
        var length32 = input.length * 32
        for (i = 0; i < length32; i += 8) {
            output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xff)
        }
        return output
    }

    /*
    * Convert a raw string to an array of little-endian words
    * Characters >255 have their high-byte silently ignored.
    */
    function rstr2binl (input) {
        var i
        var output = []
        output[(input.length >> 2) - 1] = undefined
        for (i = 0; i < output.length; i += 1) {
            output[i] = 0
        }
        var length8 = input.length * 8
        for (i = 0; i < length8; i += 8) {
            output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << (i % 32)
        }
        return output
    }

    /*
    * Calculate the MD5 of a raw string
    */
    function rstrMD5 (s) {
        return binl2rstr(binlMD5(rstr2binl(s), s.length * 8))
    }

    /*
    * Calculate the HMAC-MD5, of a key and some data (raw strings)
    */
    function rstrHMACMD5 (key, data) {
        var i
        var bkey = rstr2binl(key)
        var ipad = []
        var opad = []
        var hash
        ipad[15] = opad[15] = undefined
        if (bkey.length > 16) {
            bkey = binlMD5(bkey, key.length * 8)
        }
        for (i = 0; i < 16; i += 1) {
            ipad[i] = bkey[i] ^ 0x36363636
            opad[i] = bkey[i] ^ 0x5c5c5c5c
        }
        hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8)
        return binl2rstr(binlMD5(opad.concat(hash), 512 + 128))
    }

    /*
    * Convert a raw string to a hex string
    */
    function rstr2hex (input) {
        var hexTab = '0123456789abcdef'
        var output = ''
        var x
        var i
        for (i = 0; i < input.length; i += 1) {
            x = input.charCodeAt(i)
            output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f)
        }
        return output
    }

    /*
    * Encode a string as utf-8
    */
    function str2rstrUTF8 (input) {
        return unescape(encodeURIComponent(input))
    }

    /*
    * Take string arguments and return either raw or hex encoded strings
    */
    function rawMD5 (s) {
        return rstrMD5(str2rstrUTF8(s))
    }
    function hexMD5 (s) {
        return rstr2hex(rawMD5(s))
    }
    function rawHMACMD5 (k, d) {
        return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d))
    }
    function hexHMACMD5 (k, d) {
        return rstr2hex(rawHMACMD5(k, d))
    }

    function md5 (string, key, raw) {
        if (!key) {
            if (!raw) {
                return hexMD5(string)
            }
            return rawMD5(string)
        }
        if (!raw) {
            return hexHMACMD5(key, string)
        }
        return rawHMACMD5(key, string)
    }

    if (typeof define === 'function' && define.amd) {
        define(function () {
            return md5
        })
    } else if (typeof module === 'object' && module.exports) {
        module.exports = md5
    } else {
        $.md5 = md5
    }
})(this)

4、前端--->后端进行加密?

if (password) {
    password = salt.charAt(1) + "" + salt.charAt(5) + password + salt.charAt(0) + "" + salt.charAt(3);
    //进行md5加密
    password = md5(password);
}

5、后端--->数据库进行加密?

String salt = user.getSalt();
String newpassword = MD5Utils.formPassToDbPass(userVo.getPassword(), salt);

?

六、Js303验证(全局异常)

在项目中可以用自己定义的类去实现验证

1、先导入全局异常类?

package com.zj.seckill.util.response;


import com.zj.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;

@RestControllerAdvice
@SuppressWarnings("all")
@Slf4j
public class CatchThrowable {



    @JsonResponseResult
    @ExceptionHandler(value = BusinessException.class)
    public Object BusinessException(Model m,Exception e){
        log.warn(((BusinessException)e).getResponseResultCode().getMessage());
        return ((BusinessException)e).getResponseResultCode();
    }

    @JsonResponseResult
    @ExceptionHandler(value = BindException.class)
    public Object BindException(Model m,Exception e){
        Object[] arguments = ((BindException) e).getFieldError().getArguments();
        return Arrays.stream(arguments)
                .filter(t->t instanceof ResponseResultCode)
                .findAny()
                .orElse(ResponseResultCode.UNKNOWN);
    }

    @JsonResponseResult
    @ExceptionHandler(value = Throwable.class)
    public Object GlobalException(Model m,Exception e){
        return ResponseResultCode.UNKNOWN;
    }
}

2、加载四个类,关于UserVo中的属性类

IsMobile:

package com.zj.seckill.util.validate;

import com.zj.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.zj.seckill.util.validate;

import com.zj.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.zj.seckill.util.validate;


import com.zj.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.zj.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);
    }

}

3、在UserVo中的属性上加入注解

package com.zj.seckill.vo;


import com.zj.seckill.util.response.ResponseResultCode;
import com.zj.seckill.util.validate.IsMobile;
import com.zj.seckill.util.validate.IsRequired;
import lombok.Data;
import org.aspectj.apache.bcel.classfile.Code;

import javax.validation.constraints.NotEmpty;

@Data
public class UserVo {
    //自定义js303注解
    @IsMobile(code = ResponseResultCode.USER_ACCOUNT_NOT_FIND)
    private String mobile;

    @IsRequired(code = ResponseResultCode.USER_PASSWORD_NOT_MATCH)
    private String password;
}

4、进行测试

输入错误密码来进行测试

?

抓捕异常成功!?

这还只是项目的前期的登录功能,后期项目还会继续,今天的分享就到这了,希望能够帮助到你!

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-03-17 22:14:33  更:2022-03-17 22:14:45 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 6:16:33-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码