springboot集成kaptcha

1.下载依赖


    com.baomidou
    kaptcha-spring-boot-starter
    1.1.0

2.添加配置文件

kaptcha:
  height: 50
  width: 200
  content:
    length: 4
    source: abcdefghjklmnopqrstuvwxyz23456789
    space: 2
  font:
    color: black
    name: Arial
    size: 40
  background-color:
    from: lightGray
    to: white
  border:
    enabled: true
    color: black
    thickness: 1

3. 实现页面效果

package com.hanhuide.core.controller;

import com.baomidou.kaptcha.Kaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "验证码")
@Slf4j
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private Kaptcha kaptcha;

    @GetMapping("/render")
    @ApiOperation(value = "获取图形验证码", notes = "图形验证")
    public void render() {
        kaptcha.render();
    }

    @PostMapping("/valid")
    public void validDefaultTime(@RequestParam String code) {
        //default timeout 900 seconds
        kaptcha.validate(code);
    }

    @PostMapping("/validTime")
    public void validCustomTime(@RequestParam String code) {
        kaptcha.validate(code, 60);
    }

}

4.添加 拦截验证码异常 并统一处理,使用@RestControllerAdvice

package com.hanhuide.core.handler;

import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: maven
 * @description:
 * @author: 韩惠德
 * @create: 2019-12-27 13:29
 * @version: 1.0
 **/

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = KaptchaException.class)
    public String kaptchaExceptionHandler(KaptchaException kaptchaException) {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            return "验证码不正确";
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            return "验证码未找到";
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            return "验证码过期";
        } else {
            return "验证码渲染失败";
        }

    }

}

5. 运行 查看效果  输入http://localhost:9000/kaptcha/render

springboot集成kaptcha_第1张图片

 

 

你可能感兴趣的:(kaptcha,springboot,kaptcha,统一处理拦截)