美文网首页
6.发送短信验证码

6.发送短信验证码

作者: 呆叔么么 | 来源:发表于2019-12-24 00:30 被阅读0次

    新建ValidateCode
    com.imooc.security.core.validate.code.ValidateCode

    package com.imooc.security.core.validate.code;
    
    import java.time.LocalDateTime;
    
    /**
     * @Author:LovingLiu
     * @Description:
     * 图片验证码实体类
     * 注意: LocalDateTime 的使用
     * @Date:Created in 2019-12-22
     */
    public class ValidateCode {
        private String code;
        private LocalDateTime expireTime;
    
        public ValidateCode(String code, int expireIn){
            this.code = code;
            this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
        }
        public ValidateCode(String code, LocalDateTime expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
        public boolean isExpried() {
            return LocalDateTime.now().isAfter(expireTime);
        }
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public LocalDateTime getExpireTime() {
            return expireTime;
        }
    
        public void setExpireTime(LocalDateTime expireTime) {
            this.expireTime = expireTime;
        }
    }
    

    重构ImageCode继承ValidateCode

    package com.imooc.security.core.validate.code;
    
    import java.awt.image.BufferedImage;
    import java.time.LocalDateTime;
    
    /**
     * @Author:LovingLiu
     * @Description:
     * 图片验证码实体类
     * 注意: LocalDateTime 的使用
     * @Date:Created in 2019-12-22
     */
    public class ImageCode extends ValidateCode {
        private BufferedImage image;
        public ImageCode(BufferedImage image, String code, LocalDateTime expireTime){
            super(code,expireTime);
            this.image = image;
        }
        public ImageCode(BufferedImage image, String code,  int expireIn){
            super(code,expireIn);
            this.image = image;
        }
        public BufferedImage getImage() {
            return image;
        }
    
        public void setImage(BufferedImage image) {
            this.image = image;
        }
    }
    

    创建默认发送验证码接口SmsCodeSender
    com.imooc.security.core.validate.code.sms.SmsCodeSender

    package com.imooc.security.core.validate.code.sms;
    
    /**
     * @Author:LovingLiu
     * @Description: 短信验证码的发送接口
     * @Date:Created in 2019-12-23
     */
    public interface SmsCodeSender {
        void send(String mobile, String code);
    }
    

    实现默认发送验证码接口DefaultSmsCodeSender

    package com.imooc.security.core.validate.code.sms;
    
    /**
     * @Author:LovingLiu
     * @Description: 默认实现短信验证码的发送
     * @Date:Created in 2019-12-23
     */
    public class DefaultSmsCodeSender implements SmsCodeSender {
        @Override
        public void send(String mobile, String code) {
            // 调用短信服务商发送信息
            System.out.println("向手机: "+mobile+", 发送验证码: "+code);
        }
    }
    

    编辑生成短信验证码的逻辑SmsCodeGenerator
    com.imooc.security.core.validate.code.SmsCodeGenerator

    package com.imooc.security.core.validate.code;
    
    import com.imooc.security.core.properties.SecurityProperties;
    import org.apache.commons.lang.RandomStringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * @Author:LovingLiu
     * @Description: 短信验证码生成器
     * @Date:Created in 2019-12-23
     */
    @Component("smsCodeGenerator")
    public class SmsCodeGenerator implements ValidateCodeGenerator {
    
        @Autowired
        private SecurityProperties securityProperties;
    
        @Override
        public ValidateCode generator(HttpServletRequest request){
            String code = RandomStringUtils.randomNumeric(securityProperties.getSms().getLength());
            return new ValidateCode(code, securityProperties.getSms().getExpire());
        }
    
        public SecurityProperties getSecurityProperties() {
            return securityProperties;
        }
    
        public void setSecurityProperties(SecurityProperties securityProperties) {
            this.securityProperties = securityProperties;
        }
    }
    

    新增配置``
    com.imooc.security.core.validate.code.ValidateCodeBeanConfig

    package com.imooc.security.core.validate.code;
    
    import com.imooc.security.core.properties.SecurityProperties;
    import com.imooc.security.core.validate.code.sms.DefaultSmsCodeSender;
    import com.imooc.security.core.validate.code.sms.SmsCodeSender;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @Author:LovingLiu
     * @Description: 生成验证码逻辑的相关配置
     * @Date:Created in 2019-12-23
     */
    @Configuration
    public class ValidateCodeBeanConfig {
        @Autowired
        private SecurityProperties securityProperties;
    
        /**
         * @ConditionalOnMissingBean注解作用在@bean定义上
         * 可以给该注解传入参数例如@ConditionOnMissingBean(name = "example")
         * 这个表示如果name为“example”的bean存在,这该注解修饰的代码块不执行
         * @return
         */
        @Bean
        @ConditionalOnMissingBean(name = "imageCodeGenerator")
        public ValidateCodeGenerator imageCodeGenerator(){
            ImageCodeGenerator codeGenerator = new ImageCodeGenerator();
            codeGenerator.setSecurityProperties(securityProperties);
            return codeGenerator;
        }
    
        /**
         * @ConditionalOnMissingBean
         * 指定接口,这个表示如果没有实现该接口的类,就执行下面的代码
         * @return
         */
        @Bean
        @ConditionalOnMissingBean(SmsCodeSender.class)
        public SmsCodeSender smsCodeSender(){
            return new DefaultSmsCodeSender();
        }
    }
    

    增加获取短信验证码的接口ValidateCodeController
    com.imooc.security.core.validate.code.ValidateCodeController

    package com.imooc.security.core.validate.code;
    
    import com.imooc.security.core.validate.code.sms.SmsCodeSender;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.social.connect.web.HttpSessionSessionStrategy;
    import org.springframework.social.connect.web.SessionStrategy;
    import org.springframework.web.bind.ServletRequestBindingException;
    import org.springframework.web.bind.ServletRequestUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.context.request.ServletWebRequest;
    
    import javax.imageio.ImageIO;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * @Author:LovingLiu
     * @Description: 获取验证码图片的Controller
     * @Date:Created in 2019-12-22
     */
    @RestController
    public class ValidateCodeController  {
        public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
        // session 操作
        private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    
        // 生成验证码逻辑可配置 改造
        @Autowired
        private ValidateCodeGenerator imageCodeGenerator;
    
        @GetMapping("/code/image")
        public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
            // 1.生成验证码
            ImageCode imageCode = (ImageCode) imageCodeGenerator.generator(request);
            // 2.将随机数存放在Session中
            sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
            // 3.将图片写回响应
            ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
        }
    
        @Autowired
        private SmsCodeSender smsCodeSender;
    
        /**
         * private ValidateCodeGenerator imageCodeGenerator
         * private ValidateCodeGenerator smsCodeGenerator
         * 都能准确的找到具体的实现类,是因为 imageCodeGenerator 使用的是@Bean
         * smsCodeGenerator 使用的是@Component("smsCodeGenerator")
         *
         */
        @Autowired
        private ValidateCodeGenerator smsCodeGenerator;
    
        @GetMapping("/code/sms")
        public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
            // 1.生成验证码
            ValidateCode smsCode = smsCodeGenerator.generator(request);
            // 2.将随机数存放在Session中
            sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,smsCode);
    
            // 3.调用发送器发送验证码
            String mobile = ServletRequestUtils.getRequiredStringParameter(request,"mobile");
    
            smsCodeSender.send(mobile,smsCode.getCode());
        }
    }
    
    短信验证码发送重构逻辑

    相关文章

      网友评论

          本文标题:6.发送短信验证码

          本文链接:https://www.haomeiwen.com/subject/hptxoctx.html