功能描述:用户点击注册时,服务器段查询字段是否可行,可行就发送一封激活邮件到用户注册邮箱,并跳转到首页。待用户激活邮箱后,跳转到登录界面。
头部标签怎么复用?(即在多个页面显示)
在首页取名 —》 在注册页面复用
在controller中设置thymeleaf模板
@Controller
public class LoginController {
@RequestMapping(path = "/register", method = RequestMethod.GET)
public String getRegisterPage() {
return "/site/register";
}
}
在首页点击注册后,跳转到注册页面
提交注册数据
1、通过表单提交数据
2、服务端验证账号是否存在,邮箱是否已经被注册
// 空值处理
if (user == null) {
throw new IllegalArgumentException("参数不能为空");
}
if (StringUtils.isNullOrEmpty(user.getUsername())) {
map.put("usernameMsg","账号不能为空");
return map;
}
if (StringUtils.isNullOrEmpty(user.getPassword())) {
map.put("passwordMsg","密码不能为空");
return map;
}
if (StringUtils.isNullOrEmpty(user.getEmail())) {
map.put("emailMsg","邮箱不能为空");
return map;
}
// 验证账号
User u = userMapper.selectByName(user.getUsername());
if (u != null) {
map.put("usernameMsg","该账号已存在");
return map;
}
// 验证邮箱
u = userMapper.selectByEmail(user.getEmail());
if (u != null) {
map.put("emailMsg","该邮箱已注册");
return map;
}
3、服务器发送激活邮件
// 发送激活邮件链接
Context context = new Context();
context.setVariable("email",user.getEmail());
// http://localhost:8080/community/activation/id/code
String url = domain+contextPath+"/activation/"+user.getId()+"/"+user.getActivationCode();
context.setVariable("url",url);
String content = templateEngine.process("/mail/activation",context);
mailClient.sendMail(user.getEmail(),"激活账号",content);
/mail/activation.html
<div>
<p>
<b th:text="${email}">xxx@xxx.com</b>, 您好!
</p>
<p>
您正在注册牛客网, 这是一封激活邮件, 请点击
<a th:href="@{${url}}">此链接</a>,
激活您的牛客账号!
</p>
</div>
激活注册账号
UserService:
public int activation(int userId, String code) {
User user = userMapper.selectById(userId);
if (user.getStatus() == 1) {
return ACTIVATION_REPEATE;
}else if (user.getActivationCode().equals(code)) {
userMapper.updateUser(userId,1);
return ACTIVATION_SUCCESS;
}else {
return ACTIVATION_FAILURE;
}
}
LoginController:
@RequestMapping(path = "/activation/{userId}/{code}",method = RequestMethod.GET)
public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
int i = userService.activation(userId, code);
if (i == ACTIVATION_SUCCESS) {
model.addAttribute("msg","激活成功," +
"你的账号已经可以正常使用了!");
model.addAttribute("target","/login");
}else if (i == ACTIVATION_REPEATE) {
model.addAttribute("msg","无效操作,该账号已经激活过了" );
model.addAttribute("target","/index");
}else {
model.addAttribute("msg","激活失败,您提供的激活码不正确" );
model.addAttribute("target","/index");
}
return "/site/operate-result";
}
/site/operate-result.html
<!-- 内容 -->
<div class="jumbotron">
<p class="lead" th:text="${msg}">您的账号已经激活成功,可以正常使用了!</p>
<hr class="my-4">
<p>
系统会在 <span id="seconds" class="text-danger">8</span> 秒后自动跳转,
您也可以点此 <a id="target" th:href="@{${target}}" class="text-primary">链接</a>, 手动跳转!
</p>
</div>