图片验证码和阿里云手机短信服务

记录一下最近关于登录过程中,图片验证码和阿里的手机短信功能。

1.图片验证码

图片验证码是使用com.google.code.kaptcha第三方包来实现的,但是由于是google的jar包,所以在国内,Maven是下载不了,但好在有大佬在github中分享了(感谢大佬!,感谢开源!)。
Maven中依赖:

<dependency>
	<groupId>com.github.penggle</groupId>
	<artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

主要代码:

@Autowired
private Producer producer;
@RequestMapping("captcha")
public void captcha(HttpServletResponse response) throws IOException{
//生成文字验证码
String text = producer.createText();
//生成图片验证
BufferedImage image = producer.createImage(text);
//一般需要将验证码放到redis中,供之后验证使用
//J2CacheUtils.put(Constants.KAPTCHA_SESSION_KEY,text);
//将图片传到前台
ServletOutputStream out = response.getOutputStream();
ImageIo.write(image,"jpg",out);
}

在这过程中会出现Producer的自动装载问题,提示Producer不能自动装载,这里解决的方案就是手动装载。
编写WebConfig工具类

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

@Configuration
public class WebConfig {

    @Bean
    public Producer KaptchaProducer() {
        Properties kaptchaProperties = new Properties();
        kaptchaProperties.put("kaptcha.border", "no");
        kaptchaProperties.put("kaptcha.textproducer.char.length","4");
        kaptchaProperties.put("kaptcha.image.height","50");
        kaptchaProperties.put("kaptcha.image.width","150");
        kaptchaProperties.put("kaptcha.obscurificator.impl","com.google.code.kaptcha.impl.ShadowGimpy");
        kaptchaProperties.put("kaptcha.textproducer.font.color","black");
        kaptchaProperties.put("kaptcha.textproducer.font.size","40");
        kaptchaProperties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
        kaptchaProperties.put("kaptcha.textproducer.char.string","acdefhkmnprtwxy2345678");

        Config config = new Config(kaptchaProperties);
        return config.getProducerImpl();
    }
}

顺带提一句,在启动类中用@ComponentScan()注释来扫描并没有什么用…

2.手机短信验证码

手机短信用的是阿里云的短信服务,收费的,可以自己注册,学生党有优惠。
API文档自行查看,下面给出一个简单的demo。

@Service
public class SmsServiceImpl implements SmsService {

    protected static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class);
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "***********";
    static final String accessKeySecret = "***********";

    private IAcsClient  smsClient;

    public SendSmsResponse sendSms(String mobile, Map<String, String> smsParam) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("****");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_********")
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(JSON.toJSONString(smsParam));

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }




    public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("15000000000");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }
}

   @RequestMapping("/sendSms")
    public String sendMsg(String mobil){
        //生成6位数短信验证码
        String verifyCode = String.valueOf(new Random().nextInt(899999)+100000)
        //向手机发送验证码
        Map<String,String> map = new HashMap<>();
        map.put("code",verifyCode);
        smsService.sendSms(mobile,map);
        //将验证码存到redis中
       // J2CacheUtils.put(Constants.KAPTCHA_SESSION_KEY,verifyCode);
        //将验证码存在session中
//        HttpSession session = request.getSession();
//        JSONObject json = new JSONObject();
//        json.put(mobile,verifyCode);
//        session.setAttribute(mobile,json);
        return "login.html";
    }

至此,图片验证码和阿里云的短信服务记录完成,有问题,冷静下来,总有办法解决。

接下来,活下去吧!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值