当前位置:网站首页>Configuration and use of kaptcha verification code
Configuration and use of kaptcha verification code
2022-07-22 01:29:00 【Passing coder】
Kaptcha Introduction to verification code
◆Kaptcha It is Google's open source and highly configurable practical verification code generation tool
◆ adopt Kaptcha It can block most robot script operations
◆Kaptcha Typical application for registration 、 Sign in 、 Important information submission and other user interaction
Kaptcha Use steps
◆Kaptcha Configure verification code generation parameters
◆ Development KapatchaControler Generate captcha image
◆ Input the front desk verification code and session Compare the saved verification code
Introduce dependencies
<!-- Kaptcha Verification code components -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<!-- encryption / Decryption component -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
stay applicationContext.xml Middle configuration Kaptcha
<!-- To configure Kaptcha -->
<bean id="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<!-- Verification code pictures do not generate borders -->
<prop key="kaptcha.border">no</prop>
<!-- The width of the verification code picture is 120 Pixels -->
<prop key="kaptcha.image.width">120</prop>
<!-- The font color of the verification code image is blue -->
<prop key="kaptcha.textproducer.font.color">blue</prop>
<!-- Maximum occupancy per character 40 Pixels -->
<prop key="kaptcha.textproducer.font.size">40</prop>
<!-- The verification code contains 4 Characters -->
<prop key="kaptcha.textproducer.char.length">4</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
The test case
The method of generating the verification code image needs to be added request and response These two objects , We all know spring mvc At the bottom, it still depends on J2EE Of WEB modular , That is, there are some special scenarios in our actual development , You must use native request or response objects , Then you can write like this at this time , Put the native object in the parameter list , So at runtime spring ioc The container will dynamically inject the current request and response objects into the corresponding parameters , Like the current example , Because when designing the verification code component, he did not consider Spring Integration of , So you have to use native requests and native responses , So we put the request response in the parameter list .
package com.imooc.reader.controller;
import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
@Controller
public class KaptchaController {
@Resource
private Producer kaptchaProducer;// The attribute name should be the same as that we just defined id bring into correspondence with
@GetMapping("/verify_code")
public void createVerifyCode(HttpServletRequest request , HttpServletResponse response) throws IOException {
// Set expiration time The response immediately expires
response.setDateHeader("Expires",0);
// Cache control Do not cache any picture data Do not store Don't cache It must be verified again
response.setHeader("Cache-Control" , "no-store,no-cache,must-revalidate");
response.setHeader("Cache-Control" , "post-check=0,pre-check=0");
response.setHeader("Pragma" , "no-cache");
response.setContentType("image/png");
// Generate verification code character text
String verifyCode = kaptchaProducer.createText();
request.getSession().setAttribute("kaptchaVerifyCode",verifyCode);// Save to session among
System.out.println(request.getSession().getAttribute("kaptchaVerifyCode"));
BufferedImage image = kaptchaProducer.createImage(verifyCode);// Create verification code picture , Add the verification code just generated as a parameter
ServletOutputStream out = response.getOutputStream();// Output to browser
ImageIO.write(image, "png", out);// Output image stream
out.flush();
out.close();
}
}
Front end references :
<div class="input-group mt-4 ">
<div class="col-5 p-0">
<input type="text" id="verifyCode" name="vc" class="form-control p-4" placeholder=" Verification Code ">
</div>
<div class="col-4 p-0 pl-2 pt-0">
<!-- Captcha image -->
<img id="imgVerifyCode" src="/verify_code"
style="width: 120px;height:50px;cursor: pointer">
</div>
</div>
Refresh and verify the verification code :
// Resend request , Refresh verification code
function reloadVerifyCode(){
// Please refresh the verification code here
$("#imgVerifyCode").attr("src","/verify_code?ts=" + new Date().getTime());
}
// Click the captcha image to refresh the captcha
$("#imgVerifyCode").click(function () {
reloadVerifyCode();
});
// Click Submit button , towards /registe launch ajax request
// The submit request contains four parameters
//vc: Enter the verification code at the front desk username: user name password: password nickname: nickname
$("#btnSubmit").click(function () {
// Form verification
var username = $.trim($("#username").val());
var regex = /^.{6,10}$/;
if (!regex.test(username)) {
showTips(true, "alert-danger", " Please enter the correct format for the user name (6-10 position )");
return;
} else {
showTips(false);
}
var password = $.trim($("#password").val());
if (!regex.test(password)) {
showTips(true, "alert-danger", " Please enter the password in the correct format (6-10 position )");
return;
} else {
showTips(false);
}
$btnReg = $(this);
$btnReg.text(" Dealing with ...");
$btnReg.attr("disabled", "disabled");
// send out ajax request
$.ajax({
url: "/registe",
type: "post",
dataType: "json",
data: $("#frmLogin").serialize(),
success: function (data) {
// The result processing , According to the server return code Judge the server processing status
// The server asked to return JSON Format :
//{"code":"0","msg":" Process the message "}
console.info(" Server response :" , data);
if (data.code == "0") {
// The registration success dialog box is displayed
$("#exampleModalCenter").modal({});
$("#exampleModalCenter").modal("show");
} else {
// Server verification exception , Error message
showTips(true, "alert-danger", data.msg);
reloadVerifyCode();
$btnReg.text(" notes book ");
$btnReg.removeAttr("disabled");
}
}
});
return false;
});
@PostMapping("/registe")
@ResponseBody
public Map registe(String vc, String username, String password , String nickname , HttpServletRequest request){
// Correct verification code
String verifyCode = (String)request.getSession().getAttribute("kaptchaVerifyCode");// The property name should be the same as that set previously
// Verification code comparison
Map result = new HashMap();
if(vc == null || verifyCode == null || !vc.equalsIgnoreCase(verifyCode)){
result.put("code", "VC01");
result.put("msg", " Verification code error ");
}else{
try {
memberService.createMember(username, password, nickname);
result.put("code", "0");//0 It means that the processing is successful
result.put("msg", "success");
}catch (BussinessException ex){
ex.printStackTrace();
result.put("code", ex.getCode());
result.put("msg", ex.getMsg());
}
}
return result;
}
@PostMapping("/check_login")
@ResponseBody
public Map checkLogin(String username, String password, String vc , HttpSession session){
// Correct verification code
String verifyCode = (String)session.getAttribute("kaptchaVerifyCode");
// Verification code comparison
Map result = new HashMap();
if(vc == null || verifyCode == null || !vc.equalsIgnoreCase(verifyCode)){
result.put("code", "VC01");
result.put("msg", " Verification code error ");
}else{
try {
Member member = memberService.checkLogin(username, password);
session.setAttribute("loginMember" , member);
result.put("code", "0");
result.put("msg", "success");
}catch (BussinessException ex){
ex.printStackTrace();
result.put("code", ex.getCode());
result.put("msg", ex.getMsg());
}
}
return result;
}
边栏推荐
猜你喜欢
【集训DAY10】Linear【数学】【思维】
Using completable future to implement asynchronous callback
百度工程师眼中的云原生可观测性追踪技术
Visualization: you must know these ten data visualization tool software platforms
Advantages and disadvantages of Tongniu computer room project
【集训DAY10】Point【枚举】【双向链表】
数据库连接池
2022年化工自动化控制仪表考试试题模拟考试平台操作
酪氨酸修饰肽核酸PNA|Tyr-PNA|Bz-Tyr-PNA|99Tcm—survivinmRNA反义肽核酸的使用方法
[wechat applet] solve the problem that the code upload exceeds the size limit and the applet is subcontracted
随机推荐
int *const p=&i与int const *p=&i有什么区别
【集训DAY8】【Luogu_P6335】Staza【Tarjan】
记一次远程Debug调试Minecraft服务器插件经历
Oracle笔记 之 空值null的处理
洛谷——P1616 疯狂的采药
I.MX6U-ALPHA开发板(按键输入实验)
Industrial control software - drive framework
连接远程服务器的vscode无法格式化代码/文档(已解决)
A 股指数历史数据 API 数据接口
[semidrive source code analysis] [module bringup] 37 - LCM driven bringup process
StarkNet如何改变L2格局?
Mysql03 (Association query)
使用vscode时Tab键缩进从4个空格变为小箭头(已解决)
[dongle vulnerability notification] Apache spark command injection vulnerability scheme
SSM整合其他组件
c语言:查漏补缺(一)
rust学习笔记-rust语言基础
【集训DAY9】Maze【线段树】
Hardcore Fiddler packet capturing tool large strategy (end) Fiddler ultimate
Niu Ke brushes question 01 - Kiki de duplication of integers and sorting (C language)