秒杀项目前期之登录功能

目录

一、秒杀技术点介绍

二、秒杀学习目标

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

四、项目环境搭建

        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脚本,构建数据库,其中里面有五张表,用户表、订单表、商品表、秒杀订单表、秒杀商品表

秒杀项目前期之登录功能_第1张图片

        2、创建SpringBoot项目并配置POM

秒杀项目前期之登录功能_第2张图片pom依赖: 

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

 spring-boot-starter-freemarker
      spring-boot-starter-web
      mysql-connector-java 5.1.44
      lombok
     
      mybatis-plus-boot-starter 3.4.0
      mybatis-plus-generator 3.4.0
     
      HikariCP
     
      commons-codec
      commons-lang3 3.6
     
      spring-boot-starter-validation
     
      spring-boot-starter-data-redis


        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.1
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.5.2
        
        
        
            commons-codec
            commons-codec
        
        
            org.apache.commons
            commons-lang3
            3.12.0
        
        
        
            org.springframework.boot
            spring-boot-starter-validation
        
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            com.zaxxer
            HikariCP
        
    

        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 getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

}

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

秒杀项目前期之登录功能_第3张图片

 有几个要注意的地方

1、UserMapper一定要打@Repository注解

秒杀项目前期之登录功能_第4张图片2、在启动类一定要打以下注解 

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

秒杀项目前期之登录功能_第5张图片

        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;

/**
 * 

* 用户信息表 服务类 *

* * @author zj * @since 2022-03-15 */ public interface IUserService extends IService { 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;

/**
 * 

* 用户信息表 服务实现类 *

* * @author zj * @since 2022-03-15 */ @Service public class UserServiceImpl extends ServiceImpl 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().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;

/**
 * 

* 用户信息表 前端控制器 *

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

路径放在


秒杀项目前期之登录功能_第6张图片

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


秒杀项目






<#assign ctx>
    ${springMacroRequestContext.getContextPath()}

 good.ftl




    <#include "../common/head.ftl">


这是商品展示界面

login.ftl




    <#include "common/head.ftl"/>
    


用户登录

        6、进行测试

秒杀项目前期之登录功能_第7张图片

后端打印结果:

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

五、双重加密(盐加密,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[] 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 {

    @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[] 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 {

    @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、进行测试

输入错误密码来进行测试

秒杀项目前期之登录功能_第8张图片

秒杀项目前期之登录功能_第9张图片 

抓捕异常成功! 

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

你可能感兴趣的:(redis,java,spring,boot)