任务一.注册用户
给注册邮箱发邮件,点击激活链接进行激活,
核心内容:mysql用户表存放用户激活情况,用户激活码,md5加密的密码。注册时随机生成盐(UUID)并对密码进行MD5加密。后端和浏览器用cookie交互,或者设置path
先看User实体类:
publicclassUser {
privateintid;
privateStringusername;
privateStringpassword;
privateStringsalt;
privateStringemail;
privateinttype;
privateintstatus;
privateStringactivationCode;
privateStringheaderUrl;
privateDatecreateTime;
}
DAO
@Mapper
publicinterfaceUserMapper {
UserselectById(intid);
UserselectByName(Stringusername);
UserselectByEmail(Stringemail);
intinsertUser(Useruser);
intupdateStatus(intid, intstatus);
intupdateHeader(intid, StringheaderUrl);
intupdatePassword(intid, Stringpassword);
}
service层
publicMap<String, Object>register(Useruser) {
Map<String, Object>map=newHashMap<>();
if (user==null) {
thrownewIllegalArgumentException("参数不能为空:");
}
if (StringUtils.isBlank(user.getUsername())) {
map.put("usernameMsg", "账号不能为空");
returnmap;
}
if (StringUtils.isBlank(user.getPassword())) {
map.put("passwordMsg", "密码不能为空");
returnmap;
}
if (StringUtils.isBlank(user.getEmail())) {
map.put("emailMsg", "邮箱不能为空");
returnmap;
}
//验证账号
Useru=userMapper.selectByName(user.getUsername());
if (u!=null) {
map.put("usernameMsg", "该账号已存在");
returnmap;
}
u=userMapper.selectByEmail(user.getEmail());
if (u!=null) {
map.put("emailMsg", "该邮箱已被注册");
returnmap;
}
//注册用户
user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
user.setPassword(CommunityUtil.md5(user.getPassword() +user.getSalt()));
user.setType(0);
user.setStatus(0);
user.setActivationCode(CommunityUtil.generateUUID());
user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", newRandom().nextInt(1000)));
user.setCreateTime(newDate());
userMapper.insertUser(user);
//激活邮件
Contextcontext=newContext();
context.setVariable("email", user.getEmail());
//
Stringurl=domain+contextPath+"/activation/"+user.getId() +"/"+user.getActivationCode();
context.setVariable("url", url);
Stringcontent=templateEngine.process("/mail/activation", context);
mailClient.sendMail(user.getEmail(), "激活账号", content);
returnmap;
}
当然,邮件功能得用到JavaMailSender这个类,到这就可以实现注册了。