Get the verification code in five minutes, have you learned it?

In fact, we often see that logging in to some websites actually requires a verification code. Using verification codes is a common way for many websites now, because it is difficult for computers to recognize verification codes, so users who can recognize verification codes can be considered human beings.

In fact, we often see that logging in to some websites actually requires a verification code. Using verification codes is a common way for many websites now, because it is difficult for computers to recognize verification codes, so users who can recognize verification codes can be considered human beings.

Today we talk about the use of verification codes in Java.

Verification code generation

This effect is achieved by using the easy-captcha toolkit. First, you need to add relevant dependencies to pom.xml. The code is as follows:

<dependency>
    <groupId>com.github.whvcse</groupId>
    <artifactId>easy-captcha</artifactId>
    <version>1.6.2</version>
</dependency>

verification code format

The easy-captcha verification code tool supports GIF, Chinese, arithmetic and other types, which are realized through the following instance objects:

  • SpecCaptcha (PNG static image captcha)
  • GifCaptcha (image verification code of Gif type)
  • ChineseCaptcha (GIF type Chinese picture verification code)
  • ArithmeticCaptcha (image captcha of arithmetic type)

The character types are divided into the following types:

  • TYPE_DEFAULT: Mixed numbers and letters
  • TYPEONLYNUMBER: pure numbers
  • TYPEONLYCHAR: pure letters
  • TYPEONLYUPPER: Only uppercase letters
  • TYPEONLYLOWER: Only lowercase letters
  • TYPENUMAND_UPPER: Mixed numbers and uppercase letters

Implementation of backend logic

package com.yanx.controller;
 
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@Controller
public class KapchaController {
    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");
 
        //三个参数分别为宽、高、位数
        SpecCaptcha captcha=new SpecCaptcha(75,30,4);
 
        //设置类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
 
        //设置字体
        captcha.setCharType(Captcha.FONT_9);
 
        //验证码存入session
        httpServletRequest.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());
 
        //输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }
 
}

Here, the controller adds a defaultKaptcha() method, which intercepts and processes the path /kaptcha

Implementation of front-end logic

Create a new kaptcha.html page in the static directory, the code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
</head>
<body>
 <img src="/kaptcha" onclick="this.src='/kaptcha?t=new Date()'">
</body>
</html>

Access the backend verification code path/kaptcha, and the verification code is in the form of a picture. The onclick method can dynamically switch and display the verification code when the label is clicked.

Start the Spring Boot project, open the browser and enter the address: http://localhost:8080/ kaptcha.html

The effect is as follows:

Verification code verification

backend code

package com.yanx.controller;
 
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
 
@Controller
public class KapchaController {
    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");
 
        //三个参数分别为宽、高、位数
        SpecCaptcha captcha=new SpecCaptcha(75,30,4);
 
        //设置类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
 
        //设置字体
        captcha.setCharType(Captcha.FONT_9);
 
        //验证码存入session
        httpServletRequest.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());
 
        //输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }
 
    @GetMapping("/verify")
    @ResponseBody
    public String verify(@RequestParam("code") String code, HttpSession session){
        if(StringUtils.isEmpty(code)){
            return "验证码不能为空";
        }
        String kapchaCode = session.getAttribute("verifyCode")+"";
        if(StringUtils.isEmpty(kapchaCode)||!code.toLowerCase().equals(kapchaCode)){
            return "验证码输入错误";
        }
        return "验证成功";
    }
}

front-end code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码验证</title>
</head>
<body>
 
<img src="/kaptcha" onclick="this.src='/kaptcha?d=new Date()'">
 
<br>
<input type="text" maxlength="5" id="code" placeholder="请输入验证码"/>
<button id="verify">验证</button>
<br/>
<p id="verifyResult"></p>
 
</body>
 
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" >
  $(function(){
  //验证按钮点击事件
   $('#verify').click(function(){
    var code=$('#code').val();
    $.ajax({
      type:'GET',//方法类型
      url:'/verify?code='+code,
      success:function(result){
        $('#verifyResult').html(result);
      },
      error:function(){
        alert('请求失败');
      },
    });
   });
  });
</script>
</html>

Effect

conclusion

The function of generating verification codes is still relatively common, so record it and sort it out for future review. If there is something that helps you, I will be honored. If there are passers-by, please give me some advice!

Guess you like

Origin blog.csdn.net/weixin_42232156/article/details/129950788