https://blog.csdn.net/zhaihuilin0986/article/details/78530657
一.在 pox.xml 中 加入
二。创建一个用户实体
/**
* .
*/
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
public class Member implements Serializable {
@Id
@GenericGenerator(name = "sys_uid",strategy = "com.zhaihuilin.util.KeyGeneratorUtils",parameters = {
@Parameter(name = "k",value = "M")
})
@GeneratedValue(generator = "sys_uid")
private String id;
//用户名
@NonNull
private String username;
//昵称
private String nickname;
@NonNull
//密码
private String password;
@NonNull
//邮箱
private String email;
//电话号码
private String smscode;
//用户状态
private String state;
public Member( String username, String nickname, String password, String email, String smscode, String state) {
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
this.smscode = smscode;
this.state = state;
}
public Member(String username, String nickname, String password, String email, String state) {
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
this.state = state;
}
}
三.配置文件
1.application-dev.yml
spring:
jpa:
show-sql: true
hibernate:
ddl-auto: update
datasource:
url: jdbc:mysql://127.0.0.1:3306/sms?characterEncoding=UTF-8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
minIdle: 2
maxAction: 20
maxWaitMillis: 8000
cache:
type: redis
redis:
database: 2
host: 127.0.0.1
port: 6379
timeout: 20000
pool:
max-active: 8
min-idle: 0
max-idle: 8
max-wait: -1
2.application-.yml
server:
tomcat:
uri-encoding: utf-8
port: 8087
context-path: /
spring:
profiles:
active: dev
mail:
host: smtp.163.com
username: 邮箱
password: 邮箱的登录密码
port: 25
default-encoding: UTF-8
protocol: smtp
properties:
mail:
smth:
auth: true
starttls:
enable: true
required: true
四。编写相应的 dao service [此处省略]
五。编写工具类
//实体类主键生成策略
public class KeyGeneratorUtils extends AbstractUUIDGenerator implements Configurable {
public String k;
@Override
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
k = properties.getProperty("k");
}
@Override
public Serializable generate(SessionImplementor sessionImplementor, Object o) throws HibernateException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return k + simpleDateFormat.format(new Date());
}
}
//时间处理类
public class NormalTools {
public static String getFileType(String fileName) {
if(fileName!=null && fileName.indexOf(".")>=0) {
return fileName.substring(fileName.lastIndexOf("."), fileName.length());
}
return "";
}
/**
* 判断文件是否为图片文件
* @param fileName
* @return
*/
public static Boolean isImageFile(String fileName) {
String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
if(fileName==null) {return false;}
fileName = fileName.toLowerCase();
for(String type : img_type) {
if(fileName.endsWith(type)) {return true;}
}
return false;
}
public static String curDate(String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date());
}
public static String curDate() {
return curDate("yyyy-MM-dd HH:mm:ss");
}
}
//随机生成6位数
public class RandomTools {
/** 随机6位数 */
public static String randomCode() {
Integer res = (int)(Math.random()*1000000);
return res+"";
}
}
//加密 解密
public class SecurityUtil {
public static String md5(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
return new BigInteger(1,md.digest()).toString(16);
}
public static String md5(String username,String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(username.getBytes());
md.update(password.getBytes());
return new BigInteger(1,md.digest()).toString(16);
}
}
//非空判断
public class StringUtils {
public static boolean isNotEmpty(String str){
if(str != null && str.trim().length() != 0){
return true;
}
return false;
}
}
//邮件发送工具
@Component
public class SendEmailUtils {
@Autowired
private JavaMailSender javaMailSender; //注入 javaMailSender
@Value("${spring.mail.username}")
private String username; // 发送邮件者 邮箱 【谁发的】
/**
* 发送邮件
* @param title 标题
* @param titleWithName 是否在标题后添加 名称
* @param content 内容
* @param contentWithName 是否在内容后添加 名称
* @param email 接收者的邮箱【注册人】
*/
private void sendNormalEmail(
String title,boolean titleWithName,
String content, boolean contentWithName, String email ){
String dName="个人博客";
MimeMessage mimeMessage=null;
try {
mimeMessage= javaMailSender.createMimeMessage();//创建要发送的信息
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
helper.setFrom(new InternetAddress(username,dName,"UTF-8")); //设置 谁发送的
helper.setTo(email);//发给谁 【接收者的邮箱】
title= titleWithName?title +"-"+dName:title; //标题内容
helper.setSubject(title);//发送邮件的辩题
if(contentWithName) {
content += "
" +dName+ "
";content += "
" + NormalTools.curDate("yyyy-MM-dd HH:mm:ss")+ "
";}
helper.setText(content,true);//发送的内容 是否为html
}catch (Exception e){
e.printStackTrace();
}
javaMailSender.send(mimeMessage);
}
/**
* 发送 注册时的验证码
* @param email 接收者的邮箱【注册人】
* @param code 验证码
*/
public void sendRegisterCode(final String email, String code){
final StringBuffer sb= new StringBuffer();//实例化一个StringBuffer
sb.append("
"+email+",您好!")
.append("
此次注册的验证码是:"+code+"
");new Thread(new Runnable() {
@Override
public void run() {
sendNormalEmail("验证码", true, sb.toString(), true, email);
}
}).start();
}
/**
* 注册成功时的提示邮件
* @param email 接收的邮箱地址 【注册人】
* @param pwd 初始密码
* @param url 登陆地址
*/
public void sendRegisterSuc(final String email, String pwd, String url) {
final StringBuffer sb = new StringBuffer();
sb.append("
恭喜您,注册成功!
").append("
初始化密码是:").append(pwd).append(",请不要告诉任何人!
").append("请及时登陆网站修改密码。");
new Thread(new Runnable() {
@Override
public void run() {
sendNormalEmail("注册成功", true, sb.toString(), true, email);
}
}).start();
}
/**
* 注册成功时的提示邮件
* @param email 接收的邮箱地址 【注册人】
* @param pwd 初始密码
* @param url 登陆地址
*/
public void sendFindPwdSuc(final String email, String pwd, String url) {
final StringBuffer sb = new StringBuffer();
sb.append("
恭喜您,密码找回成功!
").append("
系统随机密码是:").append(pwd).append(",请不要告诉任何人!
").append("请及时登陆网站修改密码。");
new Thread(new Runnable() {
@Override
public void run() {
sendNormalEmail("成功找回密码", true, sb.toString(), true, email);
}
}).start();
}
/**
* 新用户注册通过
* @param email 接收邮箱地址(管理员的)
* @param nickname 注册人姓名
* @param regEmail 注册人邮箱
* @param url 地址
*/
public void sendOnRegister(final String email, String nickname, String regEmail, String url) {
final StringBuffer sb = new StringBuffer();
sb.append("姓名:").append(nickname).append("
");
sb.append("
注册邮箱:").append(regEmail).append("
");new Thread(new Runnable() {
@Override
public void run() {
sendNormalEmail("新用户注册通知", true, sb.toString(), true, email);
}
}).start();
}
}
六.编写 配置类
@Configuration
public class EmailConfig {
@Value("http://localhost:8080/member/updatePwd")
public String URL;
//管理员邮箱 此处随便写一个邮箱
@Value("[email protected]")
public String MEMEMAIL;
}
七.编写 controller
@RestController
@Log4j
@RequestMapping(value = "/member")
public class MemberController {
@Autowired
private MemberService memberService;
@Autowired
private SendEmailUtils sendEmailUtils;
@Autowired
private EmailConfig emailConfig;
/**
* 发送邮箱验证码
* @param email 接收者的邮箱 【注册人】
* @param request
* @return
*/
@RequestMapping(value = "/sendCode")
public String sendCode(
@RequestParam(value = "email",defaultValue = "",required = true) String email,
HttpServletRequest request ){
try {
String code =RandomTools.randomCode();//产生随机的验证码
request.getSession().setAttribute("registerCode",code);
//发送邮件开始 发送验证码
log.info("开始发送邮件验证码------");
sendEmailUtils.sendRegisterCode(email,code);
}catch (Exception e){
e.printStackTrace();
return "0";
}
return "1";
}
@RequestMapping(value = "/register")
public ReturnMessages register(
@RequestParam(value = "email",defaultValue = "",required = true) String email,
@RequestParam(value = "username",defaultValue = "",required = true) String username,
@RequestParam(value = "nickname",defaultValue = "",required = false) String nickname,
@RequestParam(value = "smscode",defaultValue = "",required = false) String smscode,
@RequestParam(value = "code",defaultValue = "",required = true) String code,
HttpServletRequest request
){
ReturnMessages returnMessages=null;
if (!StringUtils.isNotEmpty(email)){
return new ReturnMessages(RequestState.ERROR,"邮箱不能为空!",null);
}
if (!StringUtils.isNotEmpty(username)){
return new ReturnMessages(RequestState.ERROR,"用户名不能为空!",null);
}
if (memberService.existMemberByemail(email)){
return new ReturnMessages(RequestState.ERROR,"邮箱已存在!",null);
}
if (memberService.existMemberByusername(username)){
return new ReturnMessages(RequestState.ERROR,"用户名已存在!",null);
}
if (!StringUtils.isNotEmpty(code)){
return new ReturnMessages(RequestState.ERROR,"验证码不能为空!",null);
}
// 此处测试的时候 无法获取到 session 值
// String registerCode = (String) request.getSession().getAttribute("registerCode");
// if (!registerCode.equals(code)){
// return new ReturnMessages(RequestState.ERROR,"验证码输入不正确!",null);
// }
String pwd = RandomTools.randomCode(); //随机密码
try {
Member member=new Member();
member.setEmail(email);
member.setNickname(nickname);
member.setState(StateConstant.USER_STATE_CHECK_ING.toString());
member.setUsername(username);
member.setPassword(SecurityUtil.md5(email,pwd));
member=memberService.saveMember(member);
if (member !=null){
//注册成功后 通知注册人
sendEmailUtils.sendRegisterSuc(email,pwd, emailConfig.URL+"?username="+username+"&code="+pwd);//注册成功后
//注册成功后 通知管理员
sendEmailUtils.sendOnRegister(emailConfig.MEMEMAIL,username,email,"#");//注册成功后
return new ReturnMessages(RequestState.SUCCESS,"注册成功!",member);
}else{
return new ReturnMessages(RequestState.ERROR,"注册失败!",null);
}
} catch (Exception e) {
return new ReturnMessages(RequestState.ERROR,"注册失败!",null);
}
}
/**
* 修改密码
* @param code 初始密码
* @param newPassword 新密码
* @param request
* @return
*/
@RequestMapping(value = "/updatePwd")
public ReturnMessages updatePwd(
@RequestParam(value = "code",defaultValue = "",required = true) String code,
@RequestParam(value = "username",defaultValue = "",required = true) String username,
@RequestParam(value = "newPassword",defaultValue = "",required = true) String newPassword,
HttpServletRequest request
){
ReturnMessages returnMessages=null;
if (!StringUtils.isNotEmpty(code)){
return new ReturnMessages(RequestState.ERROR,"初始密码不能为空!",null);
}
if (!StringUtils.isNotEmpty(newPassword)){
return new ReturnMessages(RequestState.ERROR,"新密码不能为空!",null);
}
Member member = memberService.findMemberByusername(username);
if (member ==null){
return new ReturnMessages(RequestState.ERROR,"该用户不存在!",null);
}
try {
if ( StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(newPassword)){
member.setPassword(SecurityUtil.md5(member.getEmail(),newPassword));
member=memberService.updateMember(member);
if (member !=null){
return new ReturnMessages(RequestState.SUCCESS,"修改密码成功!",member);
}else{
return new ReturnMessages(RequestState.ERROR,"修改密码失败!",null);
}
}else{
return new ReturnMessages(RequestState.ERROR,"修改密码失败!",null);
}
}catch (Exception e){
return new ReturnMessages(RequestState.ERROR,"修改密码失败!",null);
}
}
/**
* 找回密码
* @param email 用户邮箱
* @param request
* @return
*/
@RequestMapping(value ="/findPwd")
public ReturnMessages findPwd(
@RequestParam(value = "email",defaultValue = "",required = true) String email,
HttpServletRequest request
){
ReturnMessages returnMessages=null;
if (!StringUtils.isNotEmpty(email)){
return new ReturnMessages(RequestState.ERROR,"邮箱不能为空!",null);
}
Member member= memberService.findMemeberByemail(email);
if (member ==null){
return new ReturnMessages(RequestState.ERROR,"该用户不存在!",null);
}
try {
String url="http:192.168.0.17:8080/member/login";
String randPwd = RandomTools.randomCode();//随机产生一个密码
member.setPassword(SecurityUtil.md5(email,randPwd));
member=memberService.updateMember(member);
//发送邮件通知 用户
sendEmailUtils.sendFindPwdSuc(email,randPwd,url);
return new ReturnMessages(RequestState.SUCCESS,"找回密码成功!",member);
}catch (Exception e){
return new ReturnMessages(RequestState.ERROR,"找回密码失败!",null);
}
}
/**
* 登录
* @param email 邮箱
* @param password 密码
* @param request
* @return
*/
@RequestMapping(value = "/login")
public ReturnMessages login(
@RequestParam(value = "email",defaultValue = "",required = true) String email,
@RequestParam(value = "password",defaultValue = "",required = true) String password,
HttpServletRequest request
){
ReturnMessages returnMessages=null;
try {
if (!StringUtils.isNotEmpty(email)){
return new ReturnMessages(RequestState.ERROR,"邮箱不能为空!",null);
}
if (!StringUtils.isNotEmpty(password)){
return new ReturnMessages(RequestState.ERROR,"密码不能为空!",null);
}
Member member=memberService.findMemeberByemail(email);
if (member== null){
return new ReturnMessages(RequestState.ERROR,"用户不存在!",null);
}
String pwd=SecurityUtil.md5(email,password);
if (member.getPassword().equals(pwd)){
return new ReturnMessages(RequestState.SUCCESS,"登录成功!",null);
}else{
return new ReturnMessages(RequestState.ERROR,"密码错误,登录失败!",null);
}
}catch (Exception e){
e.printStackTrace();
return new ReturnMessages(RequestState.ERROR,"登录失败!",null);
}
}
}
---------------------
作者:zhaihuilin0986
来源:CSDN
原文:https://blog.csdn.net/zhaihuilin0986/article/details/78530657
版权声明:本文为博主原创文章,转载请附上博文链接!