kaptcha驗證碼實現,配合spring boot使用


一、kaptcha介紹

  Kaptcha是谷歌放在github上的一個驗證碼jar包,我們可以簡單配置屬性實現驗證碼的驗證功能。

  kaptcha參數設置如下所示:

  Constant 描述 默認值
  kaptcha.border 圖片邊框,合法值:yes , no yes
  kaptcha.border.color 邊框顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
  kaptcha.border.thickness 邊框厚度,合法值:>0 1
  kaptcha.image.width 圖片寬 200
  kaptcha.image.height 圖片高 50
  kaptcha.producer.impl 圖片實現類 com.google.code.kaptcha.impl.DefaultKaptcha
  kaptcha.textproducer.impl 文本實現類 com.google.code.kaptcha.text.impl.DefaultTextCreator
  kaptcha.textproducer.char.string 文本集合,驗證碼值從此集合中獲取 abcde2345678gfynmnpwx
  kaptcha.textproducer.char.length 驗證碼長度 5
  kaptcha.textproducer.font.names 字體 Arial, Courier
  kaptcha.textproducer.font.size 字體大小 40px.
  kaptcha.textproducer.font.color 字體顏色,合法值: r,g,b 或者 white,black,blue. black
  kaptcha.textproducer.char.space 文字間隔 2
  kaptcha.noise.impl 干擾實現類 com.google.code.kaptcha.impl.DefaultNoise
  kaptcha.noise.color 干擾顏色,合法值: r,g,b 或者 white,black,blue. black
  kaptcha.obscurificator.impl 圖片樣式: 水紋com.google.code.kaptcha.impl.WaterRipple 魚眼com.google.code.kaptcha.impl.FishEyeGimpy 陰影            

  com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple 
  kaptcha.background.impl 背景實現類 com.google.code.kaptcha.impl.DefaultBackground
  kaptcha.background.clear.from 背景顏色漸變,開始顏色 light grey
  kaptcha.background.clear.to 背景顏色漸變,結束顏色 white
  kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
  kaptcha.session.key session key KAPTCHA_SESSION_KEY
  kaptcha.session.date session date KAPTCHA_SESSION_DATE

二、實現

1、引入maven依賴

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

2、編寫配置類

 1 package com.example.demo.config;
 2 
 3 import com.google.code.kaptcha.impl.DefaultKaptcha;
 4 import com.google.code.kaptcha.util.Config;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 
 8 import java.util.Properties;
 9 
10 /**
11  * @author zsh
12  * @company wlgzs
13  * @create 2019-03-10 9:37
14  * @Describe CaptchaConfig配置類
15  */
16 @Configuration
17 public class CaptchaConfig {
18 
19     @Bean(name = "captchaProducer")
20     public DefaultKaptcha getKaptchaBean(){
21         DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
22         Properties properties=new Properties();
23         properties.setProperty("kaptcha.border", "yes");
24         properties.setProperty("kaptcha.border.color", "105,179,90");
25         properties.setProperty("kaptcha.textproducer.font.color", "blue");
26         properties.setProperty("kaptcha.image.width", "125");
27         properties.setProperty("kaptcha.image.height", "45");
28         properties.setProperty("kaptcha.session.key", "code");
29         properties.setProperty("kaptcha.textproducer.char.length", "5");
30         properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑");
31         Config config=new Config(properties);
32         defaultKaptcha.setConfig(config);
33         return defaultKaptcha;
34     }
35 
36 }

3、編寫controller類

package com.example.demo;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author zsh
 * @company wlgzs
 * @create 2019-03-10 9:41
 * @Describe Captcha測試controller
 */
@Controller
public class CaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * 顯示驗證碼
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生產驗證碼字符串並保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("verifyCode", createText);
            //使用生產的驗證碼字符串返回一個BufferedImage對象並轉為byte寫入到byte數組中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定義response輸出類型為image/jpeg類型,使用response輸出流輸出圖片的byte數組
        captchaChallengeAsJpeg = 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(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    @PostMapping("/verifyCode")
    public String imgverifyControllerDefaultKaptcha(Model model, HttpSession session, String verifyCode) {
        String captchaId = (String) session.getAttribute("verifyCode");
        System.out.println("驗證碼是:" + captchaId);
        System.out.println("用戶輸入的是:" + verifyCode);
        if (!captchaId.equals(verifyCode)) {
            System.out.println("輸入錯誤");
            model.addAttribute("info", "錯誤的驗證碼");
        } else {
            System.out.println("輸入正確");
            model.addAttribute("info", "正確");
        }
        return "/index";
    }

    @GetMapping("/")
    public ModelAndView test() {
        return new ModelAndView("index");
    }

}

4、編寫測試頁面

1 -------------Kaptcha驗證碼
2 <h1 th:text="${info}"/>
3 <div>
4     <img alt="驗證碼" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha"/>
5 </div>
6 <form action="/verifyCode" method="post">
7     <input type="text" name="verifyCode"/>
8     <input type="submit" value="提交"/>
9 </form>

5、效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM