Google Kaptcha 프레임 워 크 는 로그 인 인증 코드 기능(SSM 및 SpringBoot)을 수행 합 니 다.
2.jar 패키지 가 져 오기
1.이것 은 큰 신 이 봉 인 된 프레임 워 크 이기 때문에 사용 하기 전에 관련 jar 가방 을 다운로드 해 야 합 니 다.
제 1 종:maven
<!-- -->
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
두 번 째:lib링크 열기:https://mvnrepository.com/artifact/com.github.penggle/kaptcha
3.SSM 통과 Kaptcha 간단 한 인증 코드 구현
웹.xml 에 직접 설정
인증 코드 의 일부 스타일 은 설정 을 통 해 이 루어 집 니 다.다음은 제 가 사용 하 는 demo 입 니 다.글꼴 색상 과 글꼴 크기 등 을 변경 하려 면 주석 에 따라 수정 할 수 있 습 니 다.아니면 복사 해서 붙 여 넣 어도 돼.설정 이 비교적 간단 하기 때문에 너무 많은 설명 을 하지 않 고 코드 를 직접 올 립 니 다.
<!-- -->
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- Kaptcha -->
<!-- -->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>135</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>ACDEFHKPRSTWX345975</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>43</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!-- -->
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<!-- -->
<url-pattern>/Kaptcha</url-pattern>
</servlet-mapping>
3.전단 인증 코드 의 표시 실현
div class="item-inner">
<div class="item-title label"> </div>
<input type="text" id="j_captcha" placeholder=" ">
<div class="item-input">
<img id="captcha_img" alt=" " title=" "
onclick="changeVerifyCode(this)" src="../Kaptcha"/>
</div>
</div>
function changeVerifyCode(img){
img.src="../Kaptcha?" + Math.floor(Math.random()*100);
}
설명:인증 코드 그림 의 링크 src 의"../Kaptcha"입 니 다.여기 있 는"Kaptcha"는 방금 웹.xml 의 url-pattern 설정 값 과 같 아야 합 니 다.함부로 쓰 는 것 이 아 닙 니 다.
4.백 엔 드 에서 인증번호 입력 검증
실현 사고:저 는 인증 코드 의 검증 을 정적 클래스 로 작성 한 다음 에 제어 층 에서 직접 호출 하면 됩 니 다.
인증번호 정적 클래스:
public class CodeUtil {
public static boolean checkVerifyCode(HttpServletRequest request){
String verifyCodeExpected = (String)request.getSession().getAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
// request.getParameter("verifyCodeActual");
String verifyCodeActual = HttpServletRequestUtil.getString(request, "verifyCodeActual");
if(verifyCodeActual == null || verifyCodeActual.equals(verifyCodeExpected)){
return false;
}
return true;
}}
제어 계층 호출 코드:
if(!CodeUtil.checkVerifyCode(request)){
modelMap.put("success", false);
modelMap.put("errMsg", " ");
return modelMap;
}
modelMap.put("success", false);
modelMap.put("errMsg", " ");
return modelMap;
}
만약 에 안에 인증 코드 가 통과 되 지 않 을 때 제 가 직접 처리 한 것 은 제 실제 상황 에 따라 수정 할 수 있 습 니 다.SSM 환경 에서 Kaptcha 의 사용 은 소개 되 었 습 니 다.
4.SpringBoot 는 Kaptcha 를 통 해 인증 코드 를 간단하게 실현 합 니 다.
사고방식:xml 의 형 세 를 코드 로 전환 하여 실현 한다.
package com.example.demo.config;
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 KaptchaController {
@Bean(name="captchaProducer")
public DefaultKaptcha getKaptchaBean(){
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.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
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;
}
}
controller 클래스 를 만 듭 니 다.
package com.example.demo.controller;
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.GetMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@Controller
public class ChaController {
@Autowired
private Producer captchaProducer;
@GetMapping("/getKaptchaImage")
public void getKaptchaImage(HttpServletResponse response,HttpSession session) throws Exception {
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
//request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// session
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
전단 코드:
<img id="captcha_img" alt=" " title=" "
onclick="changeVerifyCode(this)" src="../getKaptchaImage"/>
인증 코드 전환 을 누 르 고 배경 에서 인증 을 받 는 방법 에 대해 서 는 앞의 SSM 사용 방법 과 마찬가지 로 더 이상 언급 하지 않 습 니 다.springboot 프로젝트 를 직접 시작 하여 브 라 우 저 에서 인증 코드 를 가 져 오 는 인터페이스 에 직접 접근 할 수 있 습 니 다.
http://localhost:8080/getKaptchaImage
브 라 우 저 에서 인증 코드 의 그림 을 볼 수 있 습 니 다.설정 이 성공 적 이라는 것 을 설명 합 니 다.
5.Kaptcha 속성 표
총결산
위 에서 설명 한 바 와 같이 편집장 님 께 서 소개 해 주신 Google Kaptcha 프레임 워 크 는 로그 인 인증 코드 기능(SSM 과 SpringBoot)을 구현 하고 있 습 니 다.도움 이 필요 하 시 면 댓 글 을 남 겨 주세요.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
그림 미리보기 호환 i 구글 Firefox<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 TRANSITIONAL//EN" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD"...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.