<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
_<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

yaml配置

  1. spring:
  2. #配置数据源信息
  3. datasource:
  4. #配置数据源类型
  5. type: com.alibaba.druid.pool.DruidDataSource
  6. #配置连接数据库信息
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. url: jdbc:mysql://localhost:3306/appinfodb?useUnicode=yes&useSSL=false&characterEncoding=utf-8&rewriteBatchedStatements=true&serverTimezone=GMT%2B8
  9. username: root
  10. password: zax
  11. druid:
  12. # 初始化大小,最小,最大
  13. initial-size: 5
  14. min-idle: 5
  15. max-active: 30
  16. # 配置获取连接等待超时的时间
  17. max-wait: 60000
  18. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  19. time-between-eviction-runs-millis: 60000
  20. # 配置一个连接在池中最小生存的时间,单位是毫秒
  21. min-evictable-idle-time-millis: 300000
  22. mvc:
  23. # 开启put,delete请求
  24. hiddenmethod:
  25. filter:
  26. enabled: true
  27. #文件上传
  28. # 最大支持文件大小
  29. # 最大支持请求大小
  30. servlet:
  31. multipart:
  32. max-file-size: 10MB
  33. max-request-size: 10MB
  34. thymeleaf:
  35. cache: false
  36. #邮件发送
  37. mail:
  38. password: fghwjhrzpnmnjied
  39. host: smtp.qq.com
  40. username: 1507550179@qq.com
  41. default-encoding: UTF-8
  42. redis:
  43. #redis主机地址
  44. host: 192.168.207.128
  45. port: 6379
  46. password:
  47. jedis:
  48. pool:
  49. #连接池最大阻塞等待时间(使用负值表示没有限制)
  50. max-wait: 1000
  51. #连接池最大连接数(使用负值表示没有限制)
  52. max-active: 100
  53. #连接池中的最大空闲连接
  54. max-idle: 20
  55. #连接池中的最小空闲连接
  56. min-idle: 0
  57. #连接超时时间(毫秒)
  58. timeout: 30000
  59. #设置sql打印日志
  60. mybatis-plus:
  61. configuration:
  62. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  63. #配置类型别名所对应的包
  64. type-aliases-package: com.zax.appmanage.entity
  65. #配置扫描mapper映射文件的代码
  66. mapper-locations: classpath:mapper/*.xml

redis配置类

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
所谓同源是指,域名,协议,端口均相同

  1. package com.zax.appmanage.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.cache.CacheManager;
  6. import org.springframework.cache.annotation.CachingConfigurerSupport;
  7. import org.springframework.cache.annotation.EnableCaching;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  11. import org.springframework.data.redis.cache.RedisCacheManager;
  12. import org.springframework.data.redis.connection.RedisConnectionFactory;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  15. import org.springframework.data.redis.serializer.RedisSerializationContext;
  16. import org.springframework.data.redis.serializer.RedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.time.Duration;
  19. @EnableCaching //开启redis操作
  20. @Configuration
  21. public class RedisConfig extends CachingConfigurerSupport {
  22. //创建RedisTemplate类
  23. @Bean(name = "redisTemplate")
  24. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  25. RedisTemplate<String, String> template = new RedisTemplate<>();
  26. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  27. template.setConnectionFactory(factory);
  28. //key序列化方式
  29. template.setKeySerializer(redisSerializer);
  30. //value序列化
  31. template.setValueSerializer(redisSerializer);
  32. //value hashmap序列化
  33. template.setHashValueSerializer(redisSerializer);
  34. return template;
  35. }
  36. //创建缓存管理
  37. @Bean
  38. public CacheManager cacheManager(RedisConnectionFactory factory) {
  39. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  40. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  41. //解决查询缓存转换异常的问题
  42. ObjectMapper om = new ObjectMapper();
  43. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  44. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  45. jackson2JsonRedisSerializer.setObjectMapper(om);
  46. // 配置序列化(解决乱码的问题),过期时间600秒
  47. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  48. .entryTtl(Duration.ofSeconds(600))
  49. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
  50. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
  51. .disableCachingNullValues();
  52. RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
  53. .cacheDefaults(config)
  54. .build();
  55. return cacheManager;
  56. }
  57. }

创建邮件验证发送和验证控制器方法

  1. package com.zax.appmanage.controller;
  2. import com.zax.appmanage.entity.User;
  3. import com.zax.appmanage.service.IUserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.mail.MailException;
  8. import org.springframework.mail.SimpleMailMessage;
  9. import org.springframework.mail.javamail.JavaMailSender;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.*;
  12. import javax.annotation.Resource;
  13. import javax.servlet.http.HttpSession;
  14. import java.util.Random;
  15. import java.util.concurrent.TimeUnit;
  16. @Controller
  17. @CrossOrigin
  18. public class EmailController {
  19. @Autowired
  20. private RedisTemplate<String,String> redisTemplate;
  21. //自动装配JavaMailSender
  22. @Autowired
  23. private JavaMailSender mailSender;
  24. @Autowired
  25. private IUserService userService;
  26. //读取yml文件中username的值并赋值给form
  27. @Value("${spring.mail.username}")
  28. private String from;
  29. //随机生成6位数字
  30. public String getCode(String email){
  31. Random random=new Random();
  32. StringBuilder stringBuilder=new StringBuilder();
  33. for(int i=0;i<6;i++){
  34. stringBuilder.append(random.nextInt(10));
  35. }
  36. //将随机得到的验证码存入redis中设置过期时间为120s
  37. redisTemplate.opsForValue().set(email, stringBuilder.toString(), 120, TimeUnit.SECONDS);
  38. return stringBuilder.toString();
  39. }
  40. @ResponseBody
  41. //发送邮件
  42. @RequestMapping("/email")
  43. public String sendEmail(HttpSession session){
  44. SimpleMailMessage massage=new SimpleMailMessage();
  45. try {
  46. //发送者邮箱
  47. massage.setFrom(from);
  48. //收件邮箱
  49. User user =(User) session.getAttribute("user_Regis");
  50. String email = user.getEmail();
  51. System.out.println(email);
  52. massage.setTo(email);
  53. //主题信息
  54. massage.setSubject("【APP商城】");
  55. //内容
  56. massage.setText("您的验证码是"+getCode(email)+",该验证码2分钟内有效,请勿泄露给他人!");//发送内容为验证码
  57. //发送
  58. mailSender.send(massage);
  59. } catch (Exception e) {
  60. return "报错";
  61. }
  62. return "OK";
  63. }
  64. /**
  65. * 邮箱验证
  66. * @param session 用户,被发送的邮箱账号
  67. * @param yzm 输入的验证码判断
  68. * @return
  69. */
  70. @PostMapping("/yz")
  71. public String yz(HttpSession session, String yzm) {
  72. User user =(User) session.getAttribute("user_Regis");
  73. String email = user.getEmail();
  74. //根据邮箱帐号取出验证码
  75. String o = redisTemplate.opsForValue().get(email);
  76. assert o != null;
  77. if (o.equals(yzm)){
  78. userService.insert(user);
  79. return "login";
  80. }
  81. return "YZM";
  82. }
  83. }

注册和验证页面跳转控制器

  1. }
  2. //注册页面
  3. @RequestMapping("/newUser")
  4. public String newUser(){
  5. return "new_registered";
  6. }
  7. //邮箱验证页面
  8. @RequestMapping("/doRegis")
  9. public String doRegis(User user,HttpSession session){
  10. System.out.println(user.getUserName());
  11. session.setAttribute("user_Regis",user);
  12. return "YZM";
  13. }

前端页面

  1. <form th:action="@{/yz}" method="post">
  2. <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
  3. <div class="form-group has-feedback feedback-left row">
  4. <div class="col-xs-7">
  5. <input type="text" id="yz" name="yzm" placeholder="请输入验证码">
  6. </div>
  7. <div class="col-xs-5">
  8. <button type="button" name="button" id="yzm" class="btn btn-secondary btn-round" >获取验证码</button>
  9. </div>
  10. </div>
  11. <div class="form-group">
  12. <button class="btn btn-block btn-primary" id="sfyz" type="submit" >身份验证</button>
  13. </div>
  14. </form>

jquery设置验证码倒计时效果

  1. //倒计时效果
  2. $(function() {
  3. $("button[name='button']").click(function(event) {
  4. /**
  5. * 发送验证码
  6. */
  7. //使用jquery的get方法发送异步请求获取服务器
  8. $.get("/email",function(data){
  9. //data代表服务器返回的数据
  10. alert(data);
  11. },"ajax")
  12. //这里写发送验证码的代码
  13. var time = 120;
  14. settime($(this));
  15. function settime(obj){
  16. if (time==0) {
  17. $(obj).attr('disabled', false);
  18. $(obj).html("点击获取验证码");
  19. time = 120;
  20. return;
  21. } else{
  22. $(obj).attr('disabled', true);
  23. $(obj).html(time+"秒后重新发送");
  24. time--;
  25. }
  26. setTimeout(function() {
  27. settime(obj)
  28. },1000)
  29. }
  30. });
  31. })