The following shows how to integrate Kaptcha with SpringBoot. Of course, it is the same with other frameworks.
Import Kaptcha
Import pom.xml, you can choose one of the two below. It is recommended to use github, which is faster than google.
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.google.code.kaptcha</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3</version>
</dependency>
Write configuration class
import com.google.code.kaptcha.Producer;
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;
import java.util.Properties;
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer(){
Properties properties = new Properties();
properties.setProperty("kaptcah.image.width","100");
properties.setProperty("kaptcah.image.heigh","40");
properties.setProperty("kaptcah.textproducer.font.size","32");
properties.setProperty("kaptcah.textproducer.font.color","0,0,0");
properties.setProperty("kaptcah.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
properties.setProperty("kaptcah.textproducer.char.length","4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
Calling methods in the controller layer
Write in the controller layer
package com.kyw.controller;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
//登录注册
@Controller
@RequestMapping("/login")
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private Producer kaptchaProducer;
/**
* 生成验证码
* @param response
* @param session
*/
@RequestMapping(value = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response,HttpSession session){
//生成随机验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
//将验证码存入到Session
session.setAttribute("kaptcha",text);
//将图片传给前端
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
}catch (IOException e){
logger.error("响应验证码失败" + e.getMessage());
}
}
}
Effect
The picture style can be modified with the following configuration table
Visit http://localhost:8081/login/kaptcha
Kaptcha configuration table
constant |
describe |
default value |
kaptcha.border |
Does the picture have a border? |
Default true |
kaptcha.border.color |
border color |
|
kaptcha.image.width |
Verification code image width |
Default 200 |
kaptcha.image.height |
Verification code picture high |
Default 50 |
kaptcha.textproducer.font.size |
Verification code text character size |
Default is 40 |
kaptcha.session.key |
session key KAPTCHA_SESSION_KEY |
|
kaptcha.textproducer.char.length |
Verification code text character length |
Default is 5 |
kaptcha.textproducer.font.names |
Verification code text font style |
The default is new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) |
kaptcha.obscurificator.impl |
Picture style WaterRipple com.google.code.kaptcha.impl.WaterRipple FishEye com.google.code.kaptcha.impl.FishEyeGimpy Shadow com.google.code.kaptcha.impl.ShadowGimpy |
|
kaptcha.textproducer.impl |
Verification code text generation rules |
|
kaptcha.textproducer.char.space |
Verification code text character spacing |
Default is 2 |
kaptcha.noise.color |
Verification code interference color |
Default is Color.BLACK |
kaptcha.noise.impl |
Interference implementation class com.google.code.kaptcha.impl.NoNoise |
|
kaptcha.background.impl |
Background implementation class |
com.google.code.kaptcha.impl.DefaultBackground |
kaptcha.producer.impl |
Picture implementation class com.google.code.kaptcha.impl.DefaultKaptcha |
|
kaptcha.textproducer.impl |
Text implementation class com.google.code.kaptcha.text.impl.DefaultTextCreator |
|
kaptcha.textproducer.char.string |
text collection |
|
kaptcha.background.clear.from |
Background color gradient, start color |
|
kaptcha.background.clear.to |
Background color gradient, end color |
|
kaptcha.session.date |
session date KAPTCHA_SESSION_DATE |
Verification code integrated into login function
front end
Simple introduction, because the back-end interface has been written, and accessing that interface will return the image, so the front-end just writes the back-end path directly in the img. The front-end here uses the Thymeleaf template.
Add the following code to your Login.html
How to refresh the verification code?
In fact, just visit this path again, and you can refresh it directly, but this is not good, it will refresh the entire web page. What we want is a partial refresh, that is, only refresh the image.
Add a method to the a tag, click the a tag to execute the following js method, and let it use jquer to change the src value of the img tag, so that the verification code can be refreshed.
Prevent browsers from being lazy
If you change the path to the original /login/kaptcha, in theory the browser should refresh the page because we have sent another request, but in fact the browser will be lazy and think that you are requesting a static resource, and the path If it is the same every time, it will not be accessed, so when we do it, we splice a "?p=Math.random" after the url so that the request for each visit is different, which can prevent the browser from being lazy.
<input type="text" class="text" name="Kaptcha" placeholder="验证码" required="">
<div>
<img th:src="@{/login/kaptcha}" id="kaptchaImg">
<a href="javascript:refresh_kaptcha()">刷新验证码</a>
</div>
js
function refresh_kaptcha(){
$("#kaptchaImg").attr("src","/login/kaptcha?p="+Math.random())
}
rear end
The backend verifies whether the verification code is correct, and then sends the result of the front-end verification.