Spring-boot 生成验证码

pom.xml文件的配置

  • 添加依赖项
		<!-- 验证码 -->
		<dependency>
			<groupId>com.github.axet</groupId>
			<artifactId>kaptcha</artifactId>
			<version>0.0.9</version>
		</dependency>

使用CaptchaConfig类将配置注入对象池

@Configuration
public class CaptchaConfig {
    @Bean(name="captchaProducer")
    public DefaultKaptcha getKaptchaBean(){
        DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
        Properties properties=new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "125");
        properties.setProperty("kaptcha.image.height", "45");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

生成验证码的Controller

  • 将生成的验证码值加入到session中,以便后台验证。
@RestController
public class CaptchaImage {
    Producer captchaProducer = null;
    @Autowired
    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }


    @GetMapping("/doGet")
    public JSONResult doGet(HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {


        response.setDateHeader("Expires", 0);

        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        response.setHeader("Pragma", "no-cache");

        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();

        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        ImageIO.write(bi, "jpg", out);
        try {

            out.flush();
        } finally {
            out.close();
        }
        System.out.println("Captchca:" + session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
        JSONDataResult result = new JSONDataResult();
        result.getData().put("capText", capText);
        return result;
    }


}

前端页面中使用

  • 调用控制器类生成验证码,并显示在页面中
  • html块
 <div>
	<table border="0" height="60px">
		 <tr>
			<td><input type="text" id="yzm" name="yzm" style="width: 100%; height: 40px; display: inline-block;"></td>
			<td><p style="width: 20px;"></p></td>
                        <td> <img src="/doGet" alt="" id="captcha1" onclick="refreshCaptcha()" style="height: 40px; width: 100%; vertical-align: middle;">
			</td>
		</tr>
	 </table>
</div>
  • script中,点击图片刷新验证码
 function refreshCaptcha(){
            var ran = Math.floor(Math.random() * 100)
            $('#captcha1').attr('src','/doGet?' + ran);
        }

后台控制器中验证

  • Ajax请求,返回一个JSON
@PostMapping("/register")
public JSONResult register(String account,boolean male,String password,String repeatPassword,String yzm, HttpSession session) {
        int code = 400;
        String message = null;
        //从session中获取调用doGet时传入session的Constants.KAPTCHA_SESSION_KEY
        String varCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("后台:"+varCode);
        System.out.println("前台:"+yzm);

        if(!password.equals(repeatPassword)){
            message ="两次输入密码不一致";
        }
        if(!yzm.equals(varCode)){
           message = "验证码输入不正确";

        }else {

            User user = new User();
            String salt = UUID.randomUUID().toString();
            user.setMale(male);
            user.setPassword(password);
            user.setSalt(salt);
            user.setEmail(account);
            user.setStatus((byte) 1);
            try {
                userService.register(user);
                WriteEmail.emailSend(user.getEmail(), "http://localhost:8088/" + user.getSalt());

                return JSONResult.success;
            } catch (Exception e) {
                message = "邮箱已注册";
            }
        }
        return new JSONResult(code, message);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值