<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配置
spring:
#配置数据源信息
datasource:
#配置数据源类型
type: com.alibaba.druid.pool.DruidDataSource
#配置连接数据库信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/appinfodb?useUnicode=yes&useSSL=false&characterEncoding=utf-8&rewriteBatchedStatements=true&serverTimezone=GMT%2B8
username: root
password: zax
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 30
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
mvc:
# 开启put,delete请求
hiddenmethod:
filter:
enabled: true
#文件上传
# 最大支持文件大小
# 最大支持请求大小
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
thymeleaf:
cache: false
#邮件发送
mail:
password: fghwjhrzpnmnjied
host: smtp.qq.com
username: 1507550179@qq.com
default-encoding: UTF-8
redis:
#redis主机地址
host: 192.168.207.128
port: 6379
password:
jedis:
pool:
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 1000
#连接池最大连接数(使用负值表示没有限制)
max-active: 100
#连接池中的最大空闲连接
max-idle: 20
#连接池中的最小空闲连接
min-idle: 0
#连接超时时间(毫秒)
timeout: 30000
#设置sql打印日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#配置类型别名所对应的包
type-aliases-package: com.zax.appmanage.entity
#配置扫描mapper映射文件的代码
mapper-locations: classpath:mapper/*.xml
redis配置类
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
所谓同源是指,域名,协议,端口均相同
package com.zax.appmanage.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@EnableCaching //开启redis操作
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
//创建RedisTemplate类
@Bean(name = "redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(redisSerializer);
//value hashmap序列化
template.setHashValueSerializer(redisSerializer);
return template;
}
//创建缓存管理
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
创建邮件验证发送和验证控制器方法
package com.zax.appmanage.controller;
import com.zax.appmanage.entity.User;
import com.zax.appmanage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Controller
@CrossOrigin
public class EmailController {
@Autowired
private RedisTemplate<String,String> redisTemplate;
//自动装配JavaMailSender
@Autowired
private JavaMailSender mailSender;
@Autowired
private IUserService userService;
//读取yml文件中username的值并赋值给form
@Value("${spring.mail.username}")
private String from;
//随机生成6位数字
public String getCode(String email){
Random random=new Random();
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<6;i++){
stringBuilder.append(random.nextInt(10));
}
//将随机得到的验证码存入redis中设置过期时间为120s
redisTemplate.opsForValue().set(email, stringBuilder.toString(), 120, TimeUnit.SECONDS);
return stringBuilder.toString();
}
@ResponseBody
//发送邮件
@RequestMapping("/email")
public String sendEmail(HttpSession session){
SimpleMailMessage massage=new SimpleMailMessage();
try {
//发送者邮箱
massage.setFrom(from);
//收件邮箱
User user =(User) session.getAttribute("user_Regis");
String email = user.getEmail();
System.out.println(email);
massage.setTo(email);
//主题信息
massage.setSubject("【APP商城】");
//内容
massage.setText("您的验证码是"+getCode(email)+",该验证码2分钟内有效,请勿泄露给他人!");//发送内容为验证码
//发送
mailSender.send(massage);
} catch (Exception e) {
return "报错";
}
return "OK";
}
/**
* 邮箱验证
* @param session 用户,被发送的邮箱账号
* @param yzm 输入的验证码判断
* @return
*/
@PostMapping("/yz")
public String yz(HttpSession session, String yzm) {
User user =(User) session.getAttribute("user_Regis");
String email = user.getEmail();
//根据邮箱帐号取出验证码
String o = redisTemplate.opsForValue().get(email);
assert o != null;
if (o.equals(yzm)){
userService.insert(user);
return "login";
}
return "YZM";
}
}
注册和验证页面跳转控制器
}
//注册页面
@RequestMapping("/newUser")
public String newUser(){
return "new_registered";
}
//邮箱验证页面
@RequestMapping("/doRegis")
public String doRegis(User user,HttpSession session){
System.out.println(user.getUserName());
session.setAttribute("user_Regis",user);
return "YZM";
}
前端页面
<form th:action="@{/yz}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div class="form-group has-feedback feedback-left row">
<div class="col-xs-7">
<input type="text" id="yz" name="yzm" placeholder="请输入验证码">
</div>
<div class="col-xs-5">
<button type="button" name="button" id="yzm" class="btn btn-secondary btn-round" >获取验证码</button>
</div>
</div>
<div class="form-group">
<button class="btn btn-block btn-primary" id="sfyz" type="submit" >身份验证</button>
</div>
</form>
jquery设置验证码倒计时效果
//倒计时效果
$(function() {
$("button[name='button']").click(function(event) {
/**
* 发送验证码
*/
//使用jquery的get方法发送异步请求获取服务器
$.get("/email",function(data){
//data代表服务器返回的数据
alert(data);
},"ajax")
//这里写发送验证码的代码
var time = 120;
settime($(this));
function settime(obj){
if (time==0) {
$(obj).attr('disabled', false);
$(obj).html("点击获取验证码");
time = 120;
return;
} else{
$(obj).attr('disabled', true);
$(obj).html(time+"秒后重新发送");
time--;
}
setTimeout(function() {
settime(obj)
},1000)
}
});
})