javaweb端实现页面加图片验证码

注册验证码校验配置

application.properties

Kaptcha Information

kaptcha.width=150
kaptcha.height=42
kaptcha.border=no
kaptcha.textproducer.font.size=40
kaptcha.textproducer.char.space=10
kaptcha.textproducer.font.color=red
kaptcha.textproducer.font.names=仿宋,微软雅黑
kaptcha.textproducer.char.string=123456789ABCDEFGHIJKIMNPQRSTUVWXYZabcdefghijkimnpqrstuvwxyz
kaptcha.textproducer.char.length=4
kaptcha.background.clear.from=92,189,170
kaptcha.background.clear.to=255,255,255

引入依赖

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

工具包

package com.ycg.tab.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;
/**

  • @Description:
  • @Author: xjm
  • @CreateDate: 2020-02-23
    */

@Component(“numCodeUtil”)
public class NumCodeUtil {

private static Properties props = new Properties();

@Bean
public DefaultKaptcha defaultKaptcha() throws Exception {
    // 创建DefaultKaptcha对象
    DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

    // 读取配置文件
    try {
        props.load(NumCodeUtil.class.getClassLoader()
                .getResourceAsStream("application.properties"));
    }catch (Exception e) {
        e.printStackTrace();
    }

    // 将Properties文件设到DefaultKaptcha对象中
    defaultKaptcha.setConfig(new Config(props));
    return defaultKaptcha;
}

}

/**
* 获取注册页面验证码
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/getCode")
public void getCode(HttpServletRequest request, HttpServletResponse response,String type) throws IOException {
byte[] verByte = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
int expiresSeconds = RedisStaticConfig.YCG_TAB_INDEX_PHONE_VERIFY_CODE_REGISTER; // 写入缓存中的key键和设置失效时间的常量值

    try {
        //生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        log.info("captcha: {}", createText);
        // 写入redis中设置2分钟失效时间
        if(StringUtils.equals("person",type)) {
            jedisUtil.set(RedisStaticConfig.YCG_TAB_REGISTER_VERIFY_CODE + "_regVerify_person", createText, expiresSeconds);
        }else{
            jedisUtil.set(RedisStaticConfig.YCG_TAB_REGISTER_VERIFY_CODE + "_regVerify_com", createText, expiresSeconds);

        }
        //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (IOException e) {
        e.printStackTrace();
    }
    //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
    verByte = jpegOutputStream.toByteArray();
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(verByte);
    responseOutputStream.flush();
    responseOutputStream.close();
}

前端页面

  <div class="layui-row">
        <label class="layui-col-md2">
                <span class="icon-text">*</span>
            注册验证码
        </label>
        <div class="layui-col-md4">
            <input type="text" name="verifyCode" placeholder="请输入验证码(区分大小写)" style="width:100%" class="layui-input" autocomplete="off">
        </div>
   <%--     <div class="layui-col-md1">
            <span style="font-size: 12px; color: #1E9FFF">(区分大小写)</span>
        </div>--%>
        <div class="layui-col-md4">
            <div class="re-yzm" style="display:inline-block;width:170px;"><img id="verifyCode" src="" style="margin-left: 16px;height:38px;"></div>
            <span style="color: blue" class="re-yzm">换一个</span>
        </div>
    </div>

.js

// 初始化获取验证码
$(document).ready(function () {
    var url = setUrlStamp("/biPersonInfo/getCode?type=person")
    $('#verifyCode').attr("src", url)
});
// 点击更换一个验证码
$('.re-yzm').click(function () {
    var url = setUrlStamp("/biPersonInfo/getCode?type=person")
    $('#verifyCode').attr("src", url)
})

本篇文章暂且介绍到这里,具体实现根据业务来实现这里仅提供工具类

感谢支持!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值