新闻资讯

新闻资讯 媒体报道

SpringBoot+vue实现用户注册后需要邮箱激活才能登录功能

编辑:005     时间:2020-09-07

前端登录页面


前端注册页面

邮箱收到样式


核心代码介绍

pom.xml 

 <!-- 邮箱依赖 -->
<dependency> 
<groupId>javax.mail</groupId> 
<artifactId>mail</artifactId>
 <version>1.4.7</version>
</dependency>

RegistCtrler.class

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.yxyz.rest.CodeMsg;
import com.yxyz.rest.Result;
import com.yxyz.service.UserRegistService;
import com.yxyz.vo.User;import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/** * Copyright @ 2020 Zonlyn. All rights reserved.
@Description: 该类的功能描述
* @version: v1.0.0
* @author: ducl
* @date: 2020年7月7日 下午9:53:02 ** Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2020年7月7日     ducl          v1.0.0               修改原因
*/
@RestController
@CrossOrigin
public class RegistCtrler {
 @Autowired  private UserRegistService userRegistService; 
 @ApiOperation(value="用户注册")
 @PostMapping("/regist")
 public Object regist(@Valid User vo)
 {
 try  {
 return userRegistService.regist(vo);
 } 
catch (Exception e)  
{ 
e.printStackTrace(); 
} 
return Result.error(CodeMsg.SERVER_ERROR);  
}
 @Transactional 
@ApiOperation(value="用户激活")
 @GetMapping("/active")
 @ApiImplicitParams({
 @ApiImplicitParam(name = "code", value = "激活码",dataTypeClass = String.class,required = true) })
 public Object active(@RequestParam("code") String code) 
{ 
try 
 { 
return userRegistService.update(code);
 } 
catch (Exception e)  
{ 
e.printStackTrace();
 }
 return Result.error(CodeMsg.SERVER_ERROR);
 }
 @ApiOperation(value="用户登录") 
@PostMapping("/active") 
@ApiImplicitParams({ 
@ApiImplicitParam(name = "username", value = "用户名",dataTypeClass = String.class,required = true), 
@ApiImplicitParam(name = "pwd", value = "密码",dataTypeClass = String.class,required = true) })
 public Object login(@RequestParam("username") String username,@RequestParam("pwd") String pwd) 
 { 
try  
{
 return userRegistService.login(username, pwd);
 }  
catch (Exception e) 
 {
 e.printStackTrace();   
 }    
 return Result.error(CodeMsg.SERVER_ERROR); 
 }
}

UserRegistServiceImpl.class

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yxyz.dao.UserDao;
import com.yxyz.rest.CodeMsg;
import com.yxyz.rest.Result;
import com.yxyz.service.UserRegistService;
import com.yxyz.util.MailUtil;
import com.yxyz.vo.User;
/** 
* Copyright @ 2020 Zonlyn. All rights reserved.
* @Description: 该类的功能描述* @version: v1.0.0
* @author: ducl
* @date: 2020年7月7日 下午9:28:41 
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2020年7月7日     ducl          v1.0.0               修改原因
*/
@Service
public class UserRegistServiceImpl implements UserRegistService 
{  
private Logger logger = LoggerFactory.getLogger(UserRegistServiceImpl.class); 
@Autowired  
private UserDao userDao;  
@Override
 public Object regist(User vo)  
{ 
//未激活 
final Integer zt = 0;
 //生成 验证码 code   
 String code = UUID.randomUUID().toString().replace("-""");   
 vo.setCode(code); vo.setZt(zt);    
vo.setCreatedate(new Date());    
User findByUserName = userDao.findByUserName(vo.getUsername()); 
if(null != findByUserName) 
{     
 logger.error("error:注册用户名:[{}],已存在",vo.getUsername()); 
return Result.error(CodeMsg.USEREXISTS);    
}    
userDao.insert(vo);     
try  { 
new MailUtil(vo.getEmail(), code).run();
 }  
catch (Exception e) 
 {     
 logger.error("error:发送邮件失败");      
 throw new RuntimeException("发送邮件失败");   
 } 
return Result.error(CodeMsg.REGIST_SUCCESS);  
} 
@Override
 public Object update(String code)
 {   
 userDao.update(code); return Result.error(CodeMsg.ACTIVE_SUCCESS); 
 }
@Override 
public Object login(String username, String pwd) 
 {   
 Map<String,String> map = new HashMap<>(3); 
  map.put("username", username);  
  map.put("pwd", pwd);    
 User findByNameAndPwd = userDao.findByNameAndPwd(map);   
  if(null == findByNameAndPwd) 
{ 
return Result.error(CodeMsg.USENOTREXISTS);  
  }        
return Result.success(null);    
 }
}

MailUtil.class

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailUtil
 {
 private String email;// 收件人邮箱   
 private String code;// 激活码
 public MailUtil(String email, String code)
 {
 this.email = email; this.code = code;    
} 
public void run() 
{ 
// 1.创建连接对象javax.mail.Session
 // 2.创建邮件对象 javax.mail.Message 
// 3.发送一封激活邮件
 String from = "zzzzz";// 发件人电子邮箱        
String host = "cccccc"// 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)       
Properties properties = System.getProperties();// 获取系统属性
 properties.setProperty("mail.smtp.host", host);// 获取系统属性
properties.setProperty("mail.smtp.auth""true");// 打开认证 
try {
 //QQ邮箱需要下面这段代码,163邮箱不需要
 MailSSLSocketFactory sf = new MailSSLSocketFactory(); 
sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true");      
properties.put("mail.smtp.ssl.socketFactory", sf);
 // 1.获取默认session对象 
Session session = Session.getDefaultInstance(properties, new Authenticator() 
{ 
public PasswordAuthentication getPasswordAuthentication()
 {
 return new PasswordAuthentication("982976029@qq.com", "tirfaxwgffnubdcf"); // 发件人邮箱账号、授权码 
}           
 });
 // 2.创建邮件对象 
Message message = new MimeMessage(session); 
// 2.1设置发件人 
message.setFrom(new InternetAddress(from)); 
// 2.2设置接收人
 message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); 
// 2.3设置邮件主题 
message.setSubject("账号激活"); 
// 2.4设置邮件内容 
String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://139.159.147.237:8080/yxyz/active?code=" + code + "'>http://139.159.147.237:8080/yxyz/active?code=" + code + "</href></h3></body></html>";
 message.setContent(content, "text/html;charset=UTF-8"); 
// 3.发送邮件 
Transport.send(message); 
System.out.println("邮件成功发送!"); 
}
 catch (Exception e)
 { 
e.printStackTrace(); 
}
 }
}

application.yml

spring:
 profiles: 
active: dev
application-dev.yml
server: 
 port: 8080  servlet:   
 context-path: /yxyzspring: 
 datasource:   
 name: yxyz    
url: jdbc:mysql://139.159.147.237:3306/tests?serverTimezone=GMT%2b8  
username: root    
password: root123456 # 使用druid数据源    
type: com.alibaba.druid.pool.DruidDataSource   
driver-class-name: com.mysql.cj.jdbc.Driver    
filters: stat   
maxActive: 20    
initialSize: 1   
maxWait: 60000    
minIdle: 1    
timeBetweenEvictionRunsMillis: 60000    
minEvictableIdleTimeMillis: 300000    
validationQuery: select 'x'    
testWhileIdle: true    
testOnBorrow: false    
testOnReturn: false    
poolPreparedStatements: true    
maxOpenPreparedStatements:
## 该配置节点为独立的节点
mybatis: mapper-locations: 
classpath:mapping/*Mapper.xml #注意:一定要对应mapper映射xml文件的所在路径 
 type-aliases-package: com.yxyz.vo # 注意:对应实体类的路径
本内容属于网络转载,文中涉及图片等内容如有侵权,请联系编辑删除 

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

回复列表

相关推荐