前面实现了对用户名,电话,邮箱的验证后需要把信息存储到数据库中...
这里涉及到两张表--sys_user(用户表),sys_user_role(用户角色关联表)
从控制器写起--UserController
1 /** 2 * 用户新增功能实现 3 * @param sysUser 4 * @param roleId 5 * @return 6 */ 7 @PostMapping("/add") 8 @ResponseBody 9 public Results<SysUser> save(SysUser sysUser,Integer roleId) { 10 List<SysUser> results = userService.getUser(sysUser.getUserName(),sysUser.getTelephone(),sysUser.getEmail()); 11 if (results != null && results.size()>0){ 12 for (SysUser user : results){ 13 //判断用户名是否已存在 14 if (user.getUserName().equals(sysUser.getUserName())){ 15 return Results.failure(ResponseCode.USERNAME_REPEAT.getCode(), ResponseCode.USERNAME_REPEAT.getMessage()); 16 } 17 //判断手机号是否已存在 18 if (user.getTelephone().equals(sysUser.getTelephone())) { 19 return Results.failure(ResponseCode.PHONE_REPEAT.getCode(), ResponseCode.PHONE_REPEAT.getMessage()); 20 } 21 //判断邮箱是否已存在 22 if (user.getEmail().equals(sysUser.getEmail())) { 23 return Results.failure(ResponseCode.EMAIL_REPEAT.getCode(), ResponseCode.EMAIL_REPEAT.getMessage()); 24 } 25 } 26 } 27 sysUser.setStatus(1); 28 //MD5加密 29 sysUser.setPassWord(Md5Cipher.encrypt(sysUser.getPassWord())); 30 return userService.save(sysUser,roleId); 31 }
sysUser--页面接收的user信息,roleId--所选择的角色的id,注意Status(状态在数据库中不能为空,1 代表启用,可以手动设置),密码使用MD5加密
1 package com.beilin.util; 2 3 4 5 import java.security.MessageDigest; 6 import java.security.NoSuchAlgorithmException; 7 8 public class Md5Cipher { 9 10 static String salt = "Jd8785d1246asdf511234eetw2112das3365dferer1da87er523"; 11 12 public Md5Cipher() { 13 } 14 15 public static String encrypt(String string) { 16 String encryptedString = ""; 17 try { 18 byte[] strByte = string.getBytes(); 19 MessageDigest algorithm = MessageDigest.getInstance("MD5"); 20 algorithm.reset(); 21 algorithm.update(strByte); 22 byte[] md5Byte = algorithm.digest(); 23 24 StringBuffer sb = new StringBuffer(); 25 String hex = ""; 26 for (int i = 0; i < md5Byte.length; i++) { 27 hex = Integer.toHexString(0Xff & md5Byte[i]); 28 if (hex.length() == 1) { 29 sb.append('0'); 30 } 31 sb.append(hex); 32 } 33 encryptedString = sb.toString(); 34 } catch (NoSuchAlgorithmException nsae) { 35 nsae.printStackTrace(); 36 } 37 return encryptedString; 38 } 39 40 public static String encryptWithSalt(String string){ 41 return Md5Cipher.encrypt(string + salt); 42 } 43 44 public static void main(String[] argv) { 45 String str = "123456"; 46 System.out.println(Md5Cipher.encryptWithSalt(str)); 47 // BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 48 // System.out.println(bCryptPasswordEncoder.encode(str)); 49 } 50 }
Service层
UserService
UserServiceImpl
Dao层
UserDao
SQL映射文件--UserMapper.xml
接着再保存sys_user_role(SysUserRole实体类,UserRoleDao...创建过程省略)
UserRoleDao
UserRoleMapper.xml
debug测试------