一 邮件发送 在util包下建立MailClient类处理邮件发送 (发送人,收件人,主题,发送内容)
@Component
public class MailClient {
private static final Logger logger= LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to ,String subject,String content) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
}
}
发送测试
@Test
public void testTextMail() throws MessagingException {
mailClient.sendMail("873969432@qq.com","TEST"," this is wangsuhang speaking");
}
@Test
public void testHtmlMail() throws MessagingException {
Context context = new Context();
context.setVariable("username","json");
String content = templateEngine.process("/mail/activation", context);
System.out.println(content);
mailClient.sendMail("873969432@qq.com","html",content);
}
二 注册功能 CommunityUtil生成随机字符串 和 MD5加密
public static String generateUUID(){
return UUID.randomUUID().toString().replace("-","");
}
public static String md5(String key){
if(StringUtils.isBlank(key)){
return null;
}
return DigestUtils.md5DigestAsHex(key.getBytes());
}
提交表单数据(username,password,email) 调用服务层register方法处理 判断(账户,密码,邮箱是否为空) –>生成随机盐–>密码+随机盐进行MD5加密–>设置加密后的密码,账户类型,状态(是否激活),激活code,创建时间,头像 –>插入数据库 最后发送激活邮件(邮件链接activation/userId/code)
public Map<String, Object> register(User user) throws MessagingException {
Map<String , Object> map=new HashMap<>();
if(user == null ){
throw new IllegalArgumentException("用户不存在");
}
if(StringUtils.isBlank(user.getPassword())){
map.put("passwordMsg","密码不能为空");
return map;
}
if(StringUtils.isBlank(user.getUsername())){
map.put("usernameMsg","账号不能为空");
return map;
}
if(StringUtils.isBlank(user.getEmail())){
map.put("emailMsg","邮箱不能为空");
return map;
}
User u = userMapper.selectByName(user.getUsername());
if(u != null){
map.put("usernameMsg","账号已经存在");
return map;
}
User e = userMapper.selectByEmail(user.getEmail());
if(e != null){
map.put("emailMsg","邮箱已经存在");
return map;
}
user.setSalt(CommunityUtil.generateUUID().substring(0,5));
user.setPassword(CommunityUtil.md5(user.getPassword())+user.getSalt());
user.setType(0);
user.setActivationCode(CommunityUtil.generateUUID());
user.setCreateTime(new Date());
user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
userMapper.insertUser(user);
Context context=new Context();
context.setVariable("email",user.getEmail());
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);
return map;
}
控制层根据邮件链接(activation/userId/code) 激活注册用户(修改用户status)
@RequestMapping(value = "/activation/{userId}/{code}",method = RequestMethod.GET)
public String activation(@PathVariable("userId") int userId,@PathVariable("code") String code,Model model ){
int activation = userService.activation(userId, code);
if(activation == ACTIVATION_SUCCESS){
model.addAttribute("msg","激活成功,您的账号已经可以正常使用了!");
model.addAttribute("target","/login");
}else if (activation == ACTIVATION_REPEAT) {
model.addAttribute("msg","无效操作,该账号已经激活了!");
model.addAttribute("target","/index");
} else {
model.addAttribute("msg","激活失败,您提供的激活码不正确!");
model.addAttribute("target","/index");
}
return "/site/operate-result";
}
三 验证码
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","100");
properties.setProperty("kaptcha.image.height","40");
properties.setProperty("kaptcha.textproducer.font.size","32");
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
properties.setProperty("kaptcha.textproducer.char.string","123456789abcedefghijklmnopqrstuvwxyz");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
用session存入验证码到服务器端
@RequestMapping(value = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
String text = producer.createText();
BufferedImage image = producer.createImage(text);
session.setAttribute("kaptcha",text);
response.setContentType("/imgae/png");
try {
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image,"png",outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
四 前端页面 index主页修改
<a class="nav-link" th:href="@{/register}">注册</a>
跳转到注册页面
@RequestMapping(value = "/register",method = RequestMethod.GET)
public String getRegisterPage(){
return "/site/register";
}
register.html修改
<h3 class="text-center text-info border-bottom pb-3">注 册</h3>
<form class="mt-5" method="post" th:action="@{/register}">
提交表单响应服务器register方法
<input type="text"
th:class="|form-control ${usernameMsg!=null?'is-invalid':''}|"
th:value="${user!=null?user.username:''}"
id="username" name="username" placeholder="请输入您的账号!" required>
<div class="invalid-feedback" th:text="${usernameMsg}">
<input type="password"
th:class="|form-control ${passwordMsg!=null?'is-invalid':''}|"
th:value="${user!=null?user.password:''}"
id="password" name="password" placeholder="请输入您的密码!" required>
<div class="invalid-feedback" th:text="${passwordMsg}">
密码长度不能小于8位!
</div>
<div class="col-sm-10">
<input type="password" class="form-control"
th:value="${user!=null?user.password:''}"
id="confirm-password" placeholder="请再次输入密码!" required>
<div class="invalid-feedback">
两次输入的密码不一致!
</div>
<input type="email"
th:class="|form-control ${emailMsg!=null?'is-invalid':''}|"
th:value="${user!=null?user.email:''}"
id="email" name="email" placeholder="请输入您的邮箱!" required>
<div class="invalid-feedback" th:text="${emailMsg}">
该邮箱已注册!
</div>
|