찾다
백엔드 개발PHP 튜토리얼오픈소스 도구를 사용하여 웹페이지 인증 코드를 생성하는 방법

개발 도구: eclipse, kaptcha-2.3.jar 패키지.

1. 웹 프로젝트 생성

2. 새로운 Jsp 페이지 생성(컨텐츠에는 텍스트 상자, 이미지 컨테이너 및 제출 버튼이 포함됨)

rree

3. 예 이미지 인증코드(src="randomcode.jpg")의 소스를 Web.xml 파일로 구성해야 함을 알 수 있습니다. (서블릿(서블릿은 kaptcha-2.3.jar에 있음)에 맡겨 처리)

<body>
<img src="/static/imghwm/default1.png"  data-src="randomcode.jpg"  class="lazy"  alt="random"  onclick="changeR(this)"   style="max-width:90%">
<form action="check.jsp">
<input type="text" name="r">
<input type="submit" value="s">
</form>
</body>

4. kaptcha-2.3.jar 패키지가 필요하므로 다운로드한 jar 패키지를 lib로 import합니다. (복사하여 붙여넣기)

기타:

1. 웹페이지 인증코드 속성

(1) 테두리 추가

<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/randomcode.jpg</url-pattern>
</servlet-mapping>

(2) 테두리 색상

<servlet>
<init-param>
<description>图片边框,合法值:yes , no</description>
<param-name>kaptcha.border</param-name>
<param-value>yes</param-value> <!-- yes 或者 no-->
</init-param>
</servlet>

(3) 테두리 두께

<init-param>
<description>
边框颜色,合法值: r,g,b (and optional alpha) 或者white,black,blue.
</description>
<param-name>kaptcha.border.color</param-name>
<param-value>black</param-value>
</init-param>

(4) 이미지 너비

<init-param>
<description>边框厚度,合法值:>大于0 </description>
<param-name>kaptcha.border.thickness</param-name>
<param-value>1</param-value>
</init-param>

(5) 이미지 높이

<init-param>
<description>图片宽 200</description>
<param-name>kaptcha.image.width</param-name>
<param-value>200</param-value>
</init-param>

(6) 인증코드 수집

<init-param>
<description>图片高 50</description>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>

(7) 인증 코드 길이

<init-param>
<description>文本集合,验证码值从此集合中获取</description>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>1234567890</param-value> <!--纯数字 -->
//<param-value>abcde2345678gfynmnpwx</param-value> <!-- 文字加英文-->
</init-param>

(8) 글꼴

<init-param>
<description>验证码长度 默认是5 </description>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>2</param-value>
</init-param>


(9) 글꼴 크기

<init-param>
<description>字体 Arial, Courier</description>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial, Courier</param-value>
</init-param>


(10) 글꼴 색상

<init-param>
<description>字体大小 40px.</description>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>40</param-value>
</init-param>


(11) 각 인증번호 간격

<init-param>
<description>
字体颜色,合法值: r,g,b 或者 white,black,blue.
</description>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>black</param-value>
</init-param>


(12) 간섭 구현

<init-param>
<description>文字间隔 2</description>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>2</param-value>
</init-param>


(13) 간섭 색상

<init-param>
<description>干扰实现类</description>
<param-name>kaptcha.noise.impl</param-name>
<param-value>
<!-- com.google.code.kaptcha.impl.NoNoise -->
com.google.code.kaptcha.impl.DefaultNoise
</param-value>
</init-param>


(14 ) 배경 스타일

<init-param>
<description>
干扰颜色,合法值: r,g,b 或者 white,black,blue.
</description>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>


(15) 배경 구현 클래스

<init-param>
<description>
图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy
</description>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.WaterRipple
</param-value>
</init-param>

(16) 배경 그라데이션 색상

<init-param>
<description>背景实现类</description>
<param-name>kaptcha.background.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.DefaultBackground
</param-value>
</init-param>

(17) 텍스트 렌더러

<init-param>
<description>背景颜色渐变,开始颜色</description>
<param-name>kaptcha.background.clear.from</param-name>
<param-value>green</param-value>
</init-param>
<init-param>
<description>背景颜色渐变,结束颜色</description>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>white</param-value>
</init-param>

(18) 이미지의 인증코드는 Session에 저장되며, 값은

<init-param>
<description> 文字渲染器 </description>
<param-name>kaptcha.word.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultWordRenderer
</param-value>
</init-param>

입니다. (19) 이미지 구현 카테고리

<init-param>
<description> session中存放验证码的key键 </description>
<param-name>kaptcha.session.key</param-name>
<param-value>KAPTCHA_SESSION_KEY</param-value>
</init-param>

(20) 텍스트 구현 클래스(이 클래스를 다시 작성하여 중국어로 인증 코드를 구현할 수 있습니다)

<init-param>
<description>图片实现类</description>
<param-name>kaptcha.producer.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.DefaultKaptcha
</param-value>
</init-param>

중국어로 인증 코드를 구현하기 위해 텍스트 구현 클래스를 다시 작성합니다.

1. 카테고리를 생성하고 상속합니다. TextProducer 구성 및 구현(jar 패키지 내)

<init-param>
<description>文本实现类</description>
<param-name>kaptcha.textproducer.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultTextCreator
</param-value>
</init-param>

2. Web.xml 구성 수정

import com.google.code.kaptcha.text.TextProducer;
import com.google.code.kaptcha.util.Configurable;
import java.util.Random;
public class ChineseText extends Configurable implements TextProducer {
public String getText() {
int length = getConfig().getTextProducerCharLength();
String finalWord = "", firstWord = "";
int tempInt = 0;
String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f" };
Random rand = new Random();
for (int i = 0; i < length; i++) {
switch (rand.nextInt(array.length)) {
case 1:
tempInt = rand.nextInt(26) + 65;
firstWord = String.valueOf((char) tempInt);
break;
case 2:
int r1,
r2,
r3,
r4;
String strH,
strL;// high&low
r1 = rand.nextInt(3) + 11; // 前闭后开[11,14)
if (r1 == 13) {
r2 = rand.nextInt(7);
} else {
r2 = rand.nextInt(16);
}
r3 = rand.nextInt(6) + 10;
if (r3 == 10) {
r4 = rand.nextInt(15) + 1;
} else if (r3 == 15) {
r4 = rand.nextInt(15);
} else {
r4 = rand.nextInt(16);
}
strH = array[r1] + array[r2];
strL = array[r3] + array[r4];
byte[] bytes = new byte[2];
bytes[0] = (byte) (Integer.parseInt(strH, 16));
bytes[1] = (byte) (Integer.parseInt(strL, 16));
firstWord = new String(bytes);
break;
default:
tempInt = rand.nextInt(10) + 48;
firstWord = String.valueOf((char) tempInt);
break;
}
finalWord += firstWord;
}
return finalWord;
}
}

6. 확장(추가 확인 코드 구현)

1. KaptchaServlet 클래스

<init-param>
<description>文本实现类</description>
<param-name>kaptcha.textproducer.impl</param-name>
<param-value>
ChineseText
</param-value>
</init-param>
五、验证码的校验(本文是利用check.jsp来校验的)保存在Session中,其中的键值为(第十八个属性)
[html] view plain copy
<body>
<%
// 检查是否是正确的验证码
String k = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String str = request.getParameter("r");
if (k.equals(str))
out.print("true");
out.print(k + "---" + str);
%>
</body>

다시 작성 2. 구성 파일

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class KaptchaServlet extends HttpServlet implements Servlet {
private Properties props;
private Producer kaptchaProducer;
private String sessionKeyValue;
public KaptchaServlet() {
this.props = new Properties();
this.kaptchaProducer = null;
this.sessionKeyValue = null;
}
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
ImageIO.setUseCache(false);
Enumeration initParams = conf.getInitParameterNames();
while (initParams.hasMoreElements()) {
String key = (String) initParams.nextElement();
String value = conf.getInitParameter(key);
this.props.put(key, value);
}
Config config = new Config(this.props);
this.kaptchaProducer = config.getProducerImpl();
this.sessionKeyValue = config.getSessionKey();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setDateHeader("Expires", 0L);
resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
resp.setContentType("image/jpeg");
String capText = this.kaptchaProducer.createText();
String s1 = capText.substring(0, 1);
String s2 = capText.substring(1, 2);
int r = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));
BufferedImage bi = this.kaptchaProducer.createImage(s1+"+"+s2+"=?");
ServletOutputStream out = resp.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}

수정 위는 오픈 소스 도구를 사용하여 웹 페이지 인증 코드를 생성하기 위해 편집기에서 소개한 방법입니다. 질문이 있으시면 메시지를 남겨주시면 편집자가 제 시간에 답변해 드리겠습니다. 또한 PHP 중국어 웹사이트를 지원해 주신 모든 분들께 감사드립니다!

오픈 소스 도구를 사용하여 웹페이지 인증 코드를 생성하는 방법에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개Instagram API 소개Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다Laravel의 플래시 세션 데이터로 작업합니다Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축Laravel Back End : Part 2, React가있는 React 앱 구축Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱Laravel 테스트에서 단순화 된 HTTP 응답 조롱Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표2025 PHP 상황 조사 발표Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경