spring boot (three): Configure kaptcha developed image verification code

Tools and techniques:

  • vscode (right, no idea can develop a particularly cool)
  • spring boot 2.0
  • kapcha

1. Add dependence:

Input Dependent in pom.xml:

<!-- kaptcha验证码 -->
        <dependency>
        <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

2. By configuring the class configured kaptcha

First, create a config kaptcha categories:

import java.util.Properties;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        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.textproducer.char.space", "5");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        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;
    }

}

note:

  • @Configuration use annotations to register this profile
  • Examples of this kaptcha defaultKaptcha class in the spring period single embodiment mode, note name (need to get conrtoller instance variable with the same name of the bean)

Then New kaptchacontroller, to get a verification picture:

//KaptchaController.java
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class KaptchaContorller {

   @Autowired
   private Producer defaultKaptcha = null;

   @RequestMapping("/kaptcha")
   public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) {
       HttpSession session = request.getSession();
       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");

       // 返回信息为jpg
       response.setContentType("image/jpeg");

       // 生成验证码
       String capText = defaultKaptcha.createText();

       // 将验证码生成的文字保存到session 中,等待比对
       session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
       BufferedImage bufferedImage = defaultKaptcha.createImage(capText);
       // 将图片写到response中返回s
       try {

           ServletOutputStream outputStream = response.getOutputStream();
           ImageIO.write(bufferedImage, "jpg", outputStream);
           outputStream.flush();
           outputStream.close();
       } catch (Exception e) {

           e.printStackTrace();
       }
   }

}

Precautions:

@Autowired
    private Producer defaultKaptcha = null;
  • Producer variable name must be kaptchaconfig.java in defaultKaptcha instance name;
  • Each time when generating a verification code, the verification code of the contents written in the session, and then enter the verification code next determines whether the correct time can be specified to obtain the session key is determined by

Generates CAPTCHA image effects:


4824974-85ebf13edccfa53b.jpg
image

3. check codes

In the controller, we only need to come up with a verification code values ​​in the session, to do with the results of comparative post up again, you can:

  @RequestMapping(value = "/login")
    public String login(HttpServletRequest request){
        //获取生成的验证码
        String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        String inputCode = request.getParameter("kaptchaString");
        if(inputCode==null){
            return "error";
        }
        if(inputCode.equals(verifyCodeExpected)){
            return "OK";
        }else{
            return "Error";
        }
    }

    @RequestMapping("/")
    public String index(){
        return "forward:/index.html";
    }
//index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试kaptcha</title>
    <script type="text/javascript">
        function refresh() {
            document.getElementById('kaptchaimg').src="/kaptcha";
        }
    </script>
</head>
<body>
<form action="/login" method="POST">
    验证码:  <input type="text" placeholder="请输入验证码" name="kaptchaString">
    <div class="item-input">
        <img id="kaptchaimg" 
             onclick="refresh()" src="/kaptcha" />
    </div>
    <input type="submit" value="submit" />
</form>

</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_33738555/article/details/91023209