目录
2.1 构建Vo文件夹,并创建UserVo,定义mobile和password属性
2.3 定义响应封装类JsonResponseBody和JsonResponseStatus
2.4 定义userLogin(UserVo userVo,HttpServletRequest req,HttpServletResponse resp)
2.5 在IUserService中定义userLogin(UserVo userVo),并返回JsonResponseBody
4.3 在UserVo类的mobile属性中使用IsMobile注解
5.3 修改UserServiceImpl中的userLogin方法的密码校验方式
这里用了 layui 所以去 Layui 开发使用文档 - 入门指南 这里下载一个压缩包,解压之后,放在这个位置就好了
由于此项目不是前后端分离版,所以在 application.yml 中配置了 前端的位置和后缀名
spring:
freemarker:
#设置编码格式
charset: UTF-8
#后缀
suffix: .ftl
#文档类型
content-type: text/html
#模板前端
template-loader-path: classpath:/templates/
#启用模板
enabled: true
mvc:
static-path-pattern: /static/**
随便创建一个接口,用来登录
package com.jian.seckill.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class indexController {
@RequestMapping("/")
public String toLogin(){
return "login";
}
}
创建页面
登录页面:login.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<#include "common/head.ftl"/>
<script type="text/javascript" src="static/js/login.js"></script>
</head>
<body>
<div>
<blockquote class="layui-elem-quote layui-text">
用户登录
</blockquote>
<div class="layui-row" style="margin-top:15px;margin-right:40px;">
<div class="layui-form-item">
<label class="layui-form-label">用户账号</label>
<div class="layui-input-block">
<input type="text" id="username" value="18012345678" autocomplete="off"class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户密码</label>
<div class="layui-input-block">
<input type="password" id="password" value="123456" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item" style="text-align:center;margin-left:40px;">
<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>
</body>
</html>
创建一个公共类 head.ftl
用来保存总是要调用的代码
<meta charset="UTF-8">
<title>秒杀实战项目</title>
<base href="${springMacroRequestContext.contextPath}/">
<!-- layui核心js库 -->
<script src="/static/layui/layui.js" type="text/javascript"></script>
<!-- layui核心css库 -->
<link href="/static/layui/css/layui.css" rel="stylesheet" type="text/css"/>
然后浏览器输入地址,看到东西就是成功了
用户登陆
1 构建用户登录页面
登录js:login.js
通过ajax方式提交用户登录信息
let layer,form,$;
layui.use(["layer","form","jquery"],function (){
layer=layui.layer,form=layui.form,$=layui.jquery
$('#login').click(function (){
login();
});
form.render();
});
function login(){
let username=$('#username').val();
let password=$('#password').val();
console.log("username=s%,password=s%",username,password)
// 发起ajax
$.ajax({
url:"user/userLogin",
data:{
mobile:username,
password:password
},
dataType:'json',
type:'post',
async:false,
success:function (data){
console.log(data)
},
error:function (err){
console.log("登录失败")
}
})
}
2 创建UserController类实现用户登录
2.1 构建Vo文件夹,并创建UserVo,定义mobile和password属性
package com.jian.seckill.vo;
import com.jian.seckill.model.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo extends User {
private String mobile;
private String password;
}
2.2 创建UserController类
package com.jian.seckill.controller;
import com.jian.seckill.vo.UserVo;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 用户信息表 前端控制器
* </p>
*
* @author jian
* @since 2023-02-02
*/
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/userLogin")
public Map<String,Object> userLogin(UserVo userVo){
System.out.println(userVo);
Map<String,Object> json = new HashMap<>();
json.put("msg","登录成功");
json.put("success","true");
return json;
}
}
点击登录,得如下图
并且控制台也打印了数据
2.3 定义响应封装类JsonResponseBody和JsonResponseStatus
package com.jian.seckill.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
/**
* 枚举类
*/
public enum JsonResponseStatus {
SUCCESS(200,"成功"),
ERROR(500,"内部错误"),
USER_LOGIN_ERROR(7001,"账号或者密码不能为空"),
USER_MOBILE_ERROR(7002,"手机号码格式错误")
;
private int code;
private String msg;
}
package com.jian.seckill.util;
import lombok.Data;
import java.io.Serializable;
/**
* 响应封装类
* @param <T>
*/
@Data
public class JsonResponSeBody<T> implements Serializable {
private int code=200;
private String msg="ok";
private T data;
private int total=0;
/**
* 成功的构造方法
*/
public JsonResponSeBody(){
this.code=JsonResponseStatus.SUCCESS.getCode();
this.msg=JsonResponseStatus.SUCCESS.getMsg();
}
public JsonResponSeBody(JsonResponseStatus jsonResponseStatus){
this.code=jsonResponseStatus.getCode();
this.msg=jsonResponseStatus.getMsg();
}
public JsonResponSeBody(JsonResponseStatus jsonResponseStatus,T data){
this.code=jsonResponseStatus.getCode();
this.msg=jsonResponseStatus.getMsg();
this.data=data;
}
public JsonResponSeBody(JsonResponseStatus jsonResponseStatus,T data,int total){
this.code=jsonResponseStatus.getCode();
this.msg=jsonResponseStatus.getMsg();
this.data=data;
this.total=total;
}
}
2.4 定义userLogin(UserVo userVo,HttpServletRequest req,HttpServletResponse resp)
package com.jian.seckill.service;
import com.jian.seckill.model.User;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jian.seckill.util.JsonResponSeBody;
import com.jian.seckill.vo.UserVo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* <p>
* 用户信息表 服务类
* </p>
*
* @author jian
* @since 2023-02-02
*/
public interface IUserService extends IService<User> {
JsonResponSeBody<?> userLogin(UserVo userVo, HttpServletRequest req, HttpServletResponse resp);
}
2.5 在IUserService中定义userLogin(UserVo userVo),并返回JsonResponseBody
工具类
package com.jian.seckill.util;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则校验工具类
* @author jian
*/
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();
}
}
package com.jian.seckill.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jian.seckill.exception.BusinessException;
import com.jian.seckill.model.User;
import com.jian.seckill.mapper.UserMapper;
import com.jian.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.seckill.util.JsonResponSeBody;
import com.jian.seckill.util.JsonResponseStatus;
import com.jian.seckill.util.ValidatorUtils;
import com.jian.seckill.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;
/**
* <p>
* 用户信息表 服务实现类
* </p>
*
* @author jian
* @since 2023-02-02
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public JsonResponSeBody<?> userLogin(UserVo userVo, HttpServletRequest req, HttpServletResponse resp) {
//1.判断mobile和password是否为空
if(StringUtils.isEmpty(userVo.getMobile())||StringUtils.isEmpty(userVo.getPassword()))
return new JsonResponSeBody<>(JsonResponseStatus.USER_LOGIN_ERROR);
//2.判断mobile格式是否正确
if(!ValidatorUtils.isMobile(userVo.getMobile()))
return new JsonResponSeBody<>(JsonResponseStatus.USER_MOBILE_ERROR);
//3.根据用户手机号码查询用户是否存在
User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", userVo.getMobile()));
//4.校验账号
if(null==user)
return new JsonResponSeBody<>(JsonResponseStatus.USER_LOGIN_ERROR);
//5.校验密码
if (!user.getPassword().equals(userVo.getPassword()))
return new JsonResponSeBody<>(JsonResponseStatus.USER_LOGIN_ERROR);
return new JsonResponSeBody<>();
}
}
写完之后,就要修改 userController 接口
@Autowired
private IUserService userService;
@RequestMapping("/userLogin")
public JsonResponSeBody<?> userLogin(UserVo userVo, HttpServletRequest req, HttpServletResponse resp){
return userService.userLogin(userVo,req,resp);
}
运行后,经过测试,得下图
3 全局异常处理
3.1 创建BusinessException
package com.jian.seckill.exception;
import com.jian.seckill.util.JsonResponseStatus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 自定义的业务类异常
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BusinessException extends RuntimeException{
private JsonResponseStatus jsonResponseStatus;
}
3.2 创建GlobalExceptionHandler
package com.jian.seckill.exception;
import com.jian.seckill.util.JsonResponSeBody;
import com.jian.seckill.util.JsonResponseStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* SpringMvc全局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
public JsonResponSeBody<?> handler(Exception e){
// 输出异常
e.printStackTrace();
JsonResponSeBody jsonResponSeBody=null;
// 判断e的类型
if(e instanceof BusinessException){
BusinessException businessException = (BusinessException) e;
jsonResponSeBody=new JsonResponSeBody(businessException.getJsonResponseStatus());
}else{
jsonResponSeBody=new JsonResponSeBody(JsonResponseStatus.ERROR);
}
return jsonResponSeBody;
}
}
3.3 修改userLogin中的异常处理方式
# UserServiceImpl 类中的方法
@Override
public JsonResponSeBody<?> userLogin(UserVo userVo, HttpServletRequest req, HttpServletResponse resp) {
//1.判断mobile和password是否为空
if(StringUtils.isEmpty(userVo.getMobile())||StringUtils.isEmpty(userVo.getPassword()))
throw new BusinessException(JsonResponseStatus.USER_LOGIN_ERROR);
//2.判断mobile格式是否正确
if(!ValidatorUtils.isMobile(userVo.getMobile()))
throw new BusinessException(JsonResponseStatus.USER_MOBILE_ERROR);
//3.根据用户手机号码查询用户是否存在
User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", userVo.getMobile()));
//4.校验账号
if(null==user)
throw new BusinessException(JsonResponseStatus.USER_MOBILE_ERROR);
//5.校验密码
if (!user.getPassword().equals(userVo.getPassword()))
throw new BusinessException(JsonResponseStatus.USER_PASSWORD_ERROR);
return new JsonResponSeBody<>();
}
修改完之后,运行代码,可得如下图
且控制台也会抛出异常
4. 自定义注解参数校验(JSR303)
在UserVo类加上注解
public class UserVo extends User {
@NotBlank(message = "手机账号不能为空")
private String mobile;
@NotBlank(message = "登录密码不能为空")
private String password;
}
并在我们要进行验证的前面加上注解
@RequestMapping("/userLogin")
public JsonResponSeBody<?> userLogin(@Valid UserVo userVo, HttpServletRequest req, HttpServletResponse resp){
return userService.userLogin(userVo,req,resp);
}
而且还在 GlobalExceptionHandler 接口类再新加一个条件筛选,并且在得到 @NotBlank 的 message 的自定义注解,然后把值赋值到 msg 中
else if(e instanceof BindException) {
BindException bindException= (BindException) e;
jsonResponSeBody=new JsonResponSeBody(JsonResponseStatus.USER_LOGIN_ERROR);
//获取@NotBlank验证注解中的message
String msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
jsonResponSeBody.setMsg(msg);
}
4.1 创建自定义注解IsMobile
package com.jian.seckill.validator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(
// 指定自定义注解校验的规则类
validatedBy = { MobileValidator.class }
)
@Target({ FIELD })
@Retention(RUNTIME)
public @interface IsMobile {
// 默认错误消息
String message() default "手机号码格式错误";
boolean required() default true;
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
4.2 创建自定义校验规则类MobileValidator
package com.jian.seckill.validator;
import com.jian.seckill.util.ValidatorUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 自定义注解校验规则
*/
public class MobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required=false;
@Override
public void initialize(IsMobile isMobile) {
this.required= isMobile.required();
}
@Override
public boolean isValid(String mobile, ConstraintValidatorContext context) {
//如果required 不做验证的,所以就 return false
if(!required)
return false;
// 如果是要验证的,就直接进行验证
return ValidatorUtils.isMobile(mobile);
}
}
4.3 在UserVo类的mobile属性中使用IsMobile注解
运行代码,得下图
后台
5. 两次MD5加密
5.1 创建MD5Utils工具类
package com.jian.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
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) {
//d7aaa28e3b8e6c88352bd5e7c23829f9
//5512a78a188b318c074a15f9b056a712
String formPass = inputPassToFormpass("123456");
System.out.println("前端加密密码:"+formPass);
String salt = createSalt();
System.out.println("后端加密随机盐:"+salt);
String dbPass = formPassToDbPass(formPass, salt);
System.out.println("后端加密密码:"+dbPass);
System.out.println("-------------------------------------------");
String dbPass1 = inputPassToDbPass("123456", salt);
System.out.println("最终加密密码:"+dbPass1);
}
}
5.2 创建一个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)
5.3 修改UserServiceImpl中的userLogin方法的密码校验方式
//5.校验密码
// 得到随机盐+前端输入的第一道加密密码进行二次加密
String pwd= MD5Utils.formPassToDbPass(userVo.getPassword(),user.getSalt());
if (!user.getPassword().equals(pwd))
throw new BusinessException(JsonResponseStatus.USER_PASSWORD_ERROR);
5.4 在 login.ftl 中导入 js,并在 md5.js 中给予填出提示
<script type="text/javascript" src="static/js/md5.js"></script>
function login(){
let username=$('#username').val();
let password=$('#password').val();
console.log("username=s%,password=s%",username,password)
// 定义国定盐
let salt="f1g2h3j4";
// 将明文+国定盐进行密码混淆
// salt.charAt(1)+""+salt.charAt(5)+inputPass+salt.charAt(0)+""+salt.charAt(3);
let str=salt.charAt(1)+salt.charAt(5)+password+salt.charAt(0)+salt.charAt(3);
// 使用MD5对混淆后的密码进行加密处理(第一次加密,前端完成)
let inputPwd=md5(str);
// 发起ajax
$.ajax({
url:"user/userLogin",
data:{
mobile:username,
password:inputPwd
},
dataType:'json',
type:'post',
async:false,
success:function (data){
console.log(data)
if(data.code==200){
layer.msg(data.msg,{icon:6},function (){
})
}else{
layer.msg(data.msg,{icon:5})
}
},
error:function (err){
console.log("登录失败")
}
})
}
得出结果