代码实现
register.jsp
<%@page contentType="text/html; UTF-8" pageEncoding="utf-8" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/user/register" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"> <br>
<input type="submit" value="立即注册">
</form>
</body>
</html>
UserController:
/**
* 用户注册
* @param user
* @return
*/
@RequestMapping("register")
public String register(User user){
try {
userService.register(user);
return "redirect:/login.jsp";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/register.jsp";
}
}
userServiceImpl:
@Autowired
private UserDao userDao;
@Override
public void register(User user) {
// 处理业务,调用Dao
// 1,生成随机盐
String salt = saltUtils.getSalt(8);
System.out.println(salt);
// 2,将随机盐保存到数据
user.setSalt(salt);
// 3,对铭文的密码进行MD5+SALT+HASH
Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
System.out.println(md5Hash.toHex());
// 4,将生成的密码保存到数据库
user.setPassword(md5Hash.toHex());
// 5,调用dao,保存到数据库中
userDao.save(user);
}
saltUtils:生成随机盐的工具类
package shiro.demo.Untils;
import java.util.Random;
public class saltUtils {
/**
* 生成salt的静态方法
* @param n
* @return
*/
public static String getSalt(int n) {
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*()".toCharArray();
StringBuilder sb= new StringBuilder();
for (int i = 0; i < n; i++) {
char aChar = chars[new Random().nextInt(chars.length)];
sb.append(aChar);
}
return sb.toString();
}
public static void main(String[] args) {
String salt = getSalt(8);
System.out.println(salt);
}
}
userDao
void save(User user);
userDao.xml
<insert id="save" parameterType="User">
insert into t_user values(#{id},#{username},#{password},#{salt})
</insert>
效果
前端页面:
数据库保存的数据:
这里的密码是经过md5+salt+hash一系列操作形成的。