仿牛客社区开发(登录模块-注册功能)
概述
点击注册并校验成功,会返回注册成功待激活的页面,然后,页面跳转到首页,服务端发送激活邮件,点击激活后,会进入登录界面
引入Apache commons lang 依赖,便于使用StringUtils.isBlank()等方法
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
提交注册数据
CommunityUtil
实现一个工具类,用于生成随机字符串以及md5加密
UserService - register
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Value("${community.path.domain}") //域名
private String domain;
@Value("${server.servlet.context-path}") //项目路径
private String contextPath;
public Map<String,Object> register(User user){
Map<String,Object> map = new HashMap();
//空值处理
if(user == null){
throw new IllegalArgumentException("参数不能为空");
}
if(StringUtils.isBlank(user.getUserName())){
map.put("usernameMsg","账户不能为空");
return map;
}
if(StringUtils.isBlank(user.getPassword())){
map.put("passwordMsg","密码不能为空");
}
if(StringUtils.isBlank(user.getEmail())){
map.put("emailMsg","邮箱不能为空");
}
//验证账户是否存在
User user = userMapper.selectByName(user.getUserName());
if(user!=null){
map.put("usernameMsg","账户已存在");
return map;
}
//验证邮箱是否存在
user = userMapper.selectByEmail(user.getEmail());
if(user!=null){
map.put("emailMsg","邮箱已存在");
return map;
}
//注册用户
//密码加密 password+salt -> md5加密
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",new Random().nextInt(1000)));//头像
user.setCreateTime(new Date());
userMapper.insertUser(user);
//激活邮件
Context context = new Context; //thymeleaf包下的context
context.setVariable("email",user.getEmail);
//http://localhost:8080/community/activation/101/code
String url = domain+contextPath+"/activation"+user.getId()+"/"+user.setActivationCode();
context.setVariable("url",url);
String content = templateEngine.process("/mail/activation",context);
mailClient.sendMail(user.getEmail(),"激活账户",content);
return map;
}
}
html激活邮件
html邮件,使用thymeleaf模板引擎
controller - LoginController
operate-result.html
map等于null 或 为空,返回operate-result页面,显示账户激活成功,8秒后跳转到index页面(首页)
register.html
如果map不为空,跳转到register页面(注册页面),显示错误信息