优化了更多细节
SpringBoot3:前置框架
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter-test</artifactId><version>3.0.3</version><scope>test</scope></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.32</version></dependency>
你要问哪个是核心,我说我不知道!你信吗!
yaml配置文件
# 邮箱
# smtp服务器主机
# 端口号
# 邮箱登录账号
# 邮箱授权码mail:host: smtp.163.comport: 25username: password:
# redis
# 数据库
# 主机
# 端口号data:redis:database: 0host: 127.0.0.1port: 6379
username对应的值:邮箱账号
password对应的值:POP3/SMTP/IMAP服务授权码
有人就会说了,哪个什么服务授权码怎么搞
点击获取抽象版本
响应内容实体类
@Data
//json格式实体类
public class Result<T> {private Integer code;private boolean success;private T message;public Result(Integer code, boolean success, T message) {this.code = code;this.success = success;this.message = message;}public static <T> Result<T> success(){return new Result<>(0,true,null);}public static <T> Result<T> success(T data){return new Result<>(0,true,data);}public static <T> Result<T> error(T message){return new Result<>(1,false,message);}
}
采用MVC
先提供一个空白接口
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @PostMapping("/valid-Email")public Result<String> validEmail(@RequestParam("email")String email, HttpSession session){}
}
有人就会问,我能不能返回字符串(String),当然可以
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @PostMapping("/valid-Email")public String validEmail(@RequestParam("email")String email, HttpSession session){}
}
然后就报错了,说要有 return
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController {@PostMapping("/valid-Email")public Result<String> validEmail(@RequestParam("email")String email, HttpSession session){return Result.success("发送成功");}
字符串呢?
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController {
@PostMapping("/valid-Email")public String validEmail(@RequestParam("email")String email, HttpSession session){return "发送成功";}
那整数,其他类型可以吗?当然可以,只不过你需要额外添加一下内容,没有这么方便,就和Result<String>一样,额外写一个实体类+方法
有没有发现,Result<String>和Stirng的区别是多了一个调用方法
接口写完需要测试吧
测试了四次都成功了
开始写业务接口,业务接口遵守一个原则,返回类型 + 方法名 + 参数 = 业务接口
简单明了
我们先新建一个业务接口,后缀server
//发送邮箱
String sendValidateEmail(String email,String session);
然后,我们新建一个实现类,后缀以impl
然后用这个实现类去实现业务接口
@Service
public class userServiceImpl implements userService {}
记得打上注释@service
实现这个接口后,我们的接口文件里是会报错的,使用idea,alt+回车是会自动生成的
如果没有,只能手动了
@Overridepublic String sendValidateEmail(String email, String session){}
然后又报错了,因为没有return,补上就好了
因为我们的返回类型是String,所以在return里直接使用字符串即可
@Overridepublic String sendValidateEmail(String email, String session){return "站主真帅"
}
再新建一个接口,使数据库和java形成映射关系
@Mapper
public interface userMapping {}
记得打上注释@mapper
再新建一个文件夹,使java和数据库之间有一个媒介,他叫实体类(当然这是别人这么叫的)
@Data //user用户实体类 public class userEntity {private int id;private String username;//用户private String password;//密码private String nickname;//昵称private String email;//邮箱private String userPic;//头像private LocalDateTime createTime;//创建时间private LocalDateTime updateTime;//更新时间 }
记住打上注释,如果你打上这个注释报错,只有一个答案,那就是你没添
lombok框架,我偏不添加怎么办使用idea右键
点击生成
里面的内容@DATA是一样的
其次还有顺序,顺序必须要对应数据库里的顺序,报错内容还和数据库不相关,你可以尝试一下
左右两边保持一致,要不然会报错,数据库使用了下滑线,我们就要驼峰命名
MVC的结构我们就完成了,那么我们逻辑代码该写哪里呢?
实现业务接口的实现层
回到我们的实现层,就是那个打上@service注释的
@Overridepublic String sendValidateEmail(String email, String session){return "站主真帅"
}
这么下来一下子就清晰了
第一步,导入mail
@Service
public class userServiceImpl implements userService {//邮件发送器@Resource//增加代码MailSender mailSender;//增加代码public String sendValidateEmail(String email, String session){return "站主真帅"}
第二步,实现simpleMailMessage,并封装成一个对象
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;public String sendValidateEmail(String email, String session){SimpleMailMessage simpleMailMessage = new SimpleMailMessage();//增加代码return "站主真帅"}
第三步,调用封装的对象,实现具体功能
message.setFrom("yanxin_ru@163.com"); // 设置发件人邮箱(若配置默认邮箱则不用再设置)
message.setTo("xiaofeng504@qq.com"); // 设置收件人邮箱
message.setCc("xiaofeng500@qq.com"); // 设置抄报人邮箱(可以不填写)
message.setBcc("yanxin_ru@163.com"); // 设置密送人邮箱(可以不填写)
message.setSubject("安全验证code"); // 设置邮件主题
message.setText("你好!世界"); // 设置邮件文本内容
message.setSentDate(new Date()); // 设置邮件发送时间
上面是该对象的属性,下面是这次用到的
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;public String sendValidateEmail(String email, String session){SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);//增加代码simpleMailMessage.setSubject("您的安全验证邮件");//增加代码simpleMailMessage.setText("验证码:");//增加代码mailSender.send(simpleMailMessage)//增加代码return "站主真帅"}
应该迫不及待了吧,那么我们回到控制类,去实现这个功能
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @ResourceuserService service;//增加代码@PostMapping("/valid-Email")public Result<String> validEmail(@RequestParam("email")String email, HttpSession session){}
}
然后实现这个方法
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @ResourceuserService service; @PostMapping("/valid-Email")public Result<String> validEmail(@RequestParam("email")String email, HttpSession session){if (service.sendValidateEmail(email, session.getId()) != null){ //增加代码return Result.success("发送成功"); //增加代码} //增加代码return Result.error("发送失败"); //增加代码}
}
有疑问:这个session.getID()是用来完成下一步安全性的,目前写入不影响
测试一下接口
看时间,成功发送了,哎有人问为什么你会有验证码的数值,别问,问就是还没到那一步
成功发送了邮箱
接下来是随机6位数的验证码
我们只要实现,new Random方法,并封装成一个对象,调用nextInt方法
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;public String sendValidateEmail(String email, String session){Random random = new Random(); //增加代码int code = random.nextInt(899999) + 10000; //增加代码SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:");mailSender.send(simpleMailMessage)return "站主真帅"}
只完成这一步还不行,我们需要将其封装成一个整数对象,然后转入setText中,用 + 连接
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;public String sendValidateEmail(String email, String session){Random random = new Random(); //增加代码int code = random.nextInt(899999) + 10000; //增加代码SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code); //增加代码mailSender.send(simpleMailMessage)return "站主真帅"}
发送了验证码,那么这个验证码该怎么处理,这就进入了第二个环节,安全性
第一步:导入redis处理器
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;//待定:redis处理器@Resource//新增代码StringRedisTemplate template;//新增代码public String sendValidateEmail(String email, String session){Random random = new Random(); int code = random.nextInt(899999) + 10000; SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code); mailSender.send(simpleMailMessage)return "站主真帅"}
第二步:将sessionID和email封装成一个字符串
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;//待定:redis处理器@ResourceStringRedisTemplate template;public String sendValidateEmail(String email, String session){String key = "email:" + session + ":" + email;//增加代码Random random = new Random(); int code = random.nextInt(899999) + 10000; SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code); mailSender.send(simpleMailMessage)return "站主真帅"}
这里说一下为什么是sessionid,在发送的时候,httpsession对象会给我们生成一个sessionID。只要调用即可
第三步:调用opsORvalue.set方法
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;//待定:redis处理器@ResourceStringRedisTemplate template;public String sendValidateEmail(String email, String session){String key = "email:" + session + ":" + email;//增加代码Random random = new Random(); int code = random.nextInt(899999) + 10000; SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code); mailSender.send(simpleMailMessage)template.opsForValue().set(key, String.valueOf(code), 1, TimeUnit.MINUTES);//上面一句为新增代码return "站主真帅"}
我们将key,和验证码存入redis中,试试
用接口调用,在进入redis服务查看
等1分钟我们在进去看看
很硬核的等!!!!!!!
我是真的等了一分钟。。。。。。
总不可能让他一直给发邮箱吧,所以要进行一个限制
自动删除了一条,这就是为什么要用redis去存入
总不可能让他一直给发邮箱吧,所以要进行一个限制
这个限制更多是在前端,知道吧,前端对按钮进行一个时间设置,后端这个提醒就感觉怪怪的!,这边要对前端进行一个时间返回才能有用,要不然真的太怪了,我提出了警告,但是前端触发接口还是能发送,他一直发,我们一直警告,没用啊1!!
代码实现还是要给的
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;//待定:redis处理器@ResourceStringRedisTemplate template;public String sendValidateEmail(String email, String session){String key = "email:" + session + ":" + email;if (Boolean.TRUE.equals(template.hasKey(key))) {//增加代码Long expire = Optional.ofNullable(template.getExpire(key, TimeUnit.SECONDS)).orElse(0L);//增加代码if (expire > 120)//增加代码return "请稍后再试!";//增加代码}Random random = new Random(); int code = random.nextInt(899999) + 10000; SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code); mailSender.send(simpleMailMessage)template.opsForValue().set(key, String.valueOf(code), 1, TimeUnit.MINUTES);//上面一句为新增代码return "站主真帅"}
用异常优化一下,业务实现层完整代码如下
@Service
public class userServiceImpl implements userService {//邮件发送器@ResourceMailSender mailSender;//待定:redis处理器@ResourceStringRedisTemplate template;
@Overridepublic String sendValidateEmail(String email, String session) {//数据搬运工,将key搬运来String key = "email:" + session + ":" + email;//处理数据,深加工,if (Boolean.TRUE.equals(template.hasKey(key))) {Long expire = Optional.ofNullable(template.getExpire(key, TimeUnit.SECONDS)).orElse(0L);if (expire > 120)return "请稍后再试!";}Random random = new Random();int code = random.nextInt(899999) + 10000;SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setFrom("yanxin_ru@163.com");simpleMailMessage.setTo(email);simpleMailMessage.setSubject("您的安全验证邮件");simpleMailMessage.setText("验证码:" + code);try {mailSender.send(simpleMailMessage);template.opsForValue().set(key, String.valueOf(code), 1, TimeUnit.MINUTES);return "发送成功";} catch (MailException e) {e.printStackTrace();return "发送失败";}}
}
哎。那么mapper层呢?当然发送邮箱没有用到,但是如果你不想用redis数据库,那么用mapper去实现也是可以的
是个人都能访问我们接口吗?这肯定是不行的
validation框架,对接口进行一个限制,打上@Validated
@Validated//额外添加注释
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @PostMapping("/valid-Email")public Result<String> validEmail(@RequestParam("email")String email, HttpSession session){//内容省略/。。。。。}
}
validation官方提供了关于邮箱的验证
我们只要在参数前添加一个@Email就好了
@Validated//额外添加注释
@RestController
@RequestMapping("/api/auth")//父路径,可写可不写
public class userController { @PostMapping("/valid-Email")public Result<String> validEmail(@Email @RequestParam("email")String email, HttpSession session){//内容省略/。。。。。}
}
发送邮箱甚至连判断都没用上