Home Backend Development PHP Tutorial How to use open source tools to create web page verification codes

How to use open source tools to create web page verification codes

Jan 13, 2017 pm 02:52 PM

Development tools: eclipse, kaptcha-2.3.jar package.

1. Create a Web project;

2. Create a new Jsp page (the content includes a text box, an image container, and a submit button)

1

2

3

4

5

6

7

<body>

<img alt="random" src="randomcode.jpg" onclick="changeR(this)" style="cursor: pointer;">

<form action="check.jsp">

<input type="text" name="r">

<input type="submit" value="s">

</form>

</body>

Copy after login

3. Yes It can be seen that the source of the image verification code (src="randomcode.jpg") needs to be configured with the Web.xml file. (Leave it to the Servlet (the servlet is in kaptcha-2.3.jar) for processing)

1

2

3

4

5

6

7

8

<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>

Copy after login

4. Since the kaptcha-2.3.jar package is required, import the downloaded jar package into lib. (Just copy and paste)

Others:

1. Attributes of web page verification code

(1) Add border

1

2

3

4

5

6

7

<servlet>

<init-param>

<description>图片边框,合法值:yes , no</description>

<param-name>kaptcha.border</param-name>

<param-value>yes</param-value> <!-- yes 或者 no-->

</init-param>

</servlet>

Copy after login

(2) Border Color

1

2

3

4

5

6

7

<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>

Copy after login

(3) Border thickness

1

2

3

4

5

<init-param>

<description>边框厚度,合法值:>大于0 </description>

<param-name>kaptcha.border.thickness</param-name>

<param-value>1</param-value>

</init-param>

Copy after login

(4) Image width

1

2

3

4

5

<init-param>

<description>图片宽 200</description>

<param-name>kaptcha.image.width</param-name>

<param-value>200</param-value>

</init-param>

Copy after login

(5) Image height

1

2

3

4

5

<init-param>

<description>图片高 50</description>

<param-name>kaptcha.image.height</param-name>

<param-value>50</param-value>

</init-param>

Copy after login

(6) Verification code collection

1

2

3

4

5

6

<init-param>

<description>文本集合,验证码值从此集合中获取</description>

<param-name>kaptcha.textproducer.char.string</param-name>

<param-value>1234567890</param-value> <!--纯数字 -->

//<param-value>abcde2345678gfynmnpwx</param-value> <!-- 文字加英文-->

</init-param>

Copy after login

(7) Verification code length

1

2

3

4

5

<init-param>

<description>验证码长度 默认是5 </description>

<param-name>kaptcha.textproducer.char.length</param-name>

<param-value>2</param-value>

</init-param>

Copy after login

(8) Font

1

2

3

4

5

<init-param>

<description>字体 Arial, Courier</description>

<param-name>kaptcha.textproducer.font.names</param-name>

<param-value>Arial, Courier</param-value>

</init-param>

Copy after login


(9) Font size

1

2

3

4

5

<init-param>

<description>字体大小 40px.</description>

<param-name>kaptcha.textproducer.font.size</param-name>

<param-value>40</param-value>

</init-param>

Copy after login


(10) Font color

1

2

3

4

5

6

7

<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>

Copy after login


(11)The interval between each verification code

1

2

3

4

5

<init-param>

<description>文字间隔 2</description>

<param-name>kaptcha.textproducer.char.space</param-name>

<param-value>2</param-value>

</init-param>

Copy after login


(Twelve) Interference Realization

1

2

3

4

5

6

7

8

<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>

Copy after login


(Thirteen) Interference Color

1

2

3

4

5

6

7

<init-param>

<description>

干扰颜色,合法值: r,g,b 或者 white,black,blue.

</description>

<param-name>kaptcha.noise.color</param-name>

<param-value>black</param-value>

</init-param>

Copy after login


(Fourteen) Background style

1

2

3

4

5

6

7

8

9

10

11

<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>

Copy after login


(Fifteen) Background implementation class

1

2

3

4

5

6

7

<init-param>

<description>背景实现类</description>

<param-name>kaptcha.background.impl</param-name>

<param-value>

com.google.code.kaptcha.impl.DefaultBackground

</param-value>

</init-param>

Copy after login

(Sixteen) Background gradient color

1

2

3

4

5

6

7

8

9

10

<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>

Copy after login

(17) Text renderer

1

2

3

4

5

6

7

<init-param>

<description> 文字渲染器 </description>

<param-name>kaptcha.word.impl</param-name>

<param-value>

com.google.code.kaptcha.text.impl.DefaultWordRenderer

</param-value>

</init-param>

Copy after login

(18) The verification code of the image will be saved in the Session, and the value is

1

2

3

4

5

<init-param>

<description> session中存放验证码的key键 </description>

<param-name>kaptcha.session.key</param-name>

<param-value>KAPTCHA_SESSION_KEY</param-value>

</init-param>

Copy after login

(19) Image implementation category

1

2

3

4

5

6

7

<init-param>

<description>图片实现类</description>

<param-name>kaptcha.producer.impl</param-name>

<param-value>

com.google.code.kaptcha.impl.DefaultKaptcha

</param-value>

</init-param>

Copy after login

(20) Text implementation class (you can rewrite this class to implement the verification code in Chinese)

1

2

3

4

5

6

7

<init-param>

<description>文本实现类</description>

<param-name>kaptcha.textproducer.impl</param-name>

<param-value>

com.google.code.kaptcha.text.impl.DefaultTextCreator

</param-value>

</init-param>

Copy after login

Rewrite the text implementation class to implement the verification code in Chinese:

1. Create a category, inherit Configurable and implement TextProducer (in the jar package)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

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;

}

}

Copy after login

2. Modify the Web.xml configuration

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<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>

Copy after login

6. Extension (implementation of addition verification code)

1. Rewrite the KaptchaServlet class

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

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();

}

}

}

Copy after login

2. Modify the configuration file

1

2

3

4

<servlet>

<servlet-name>Kaptcha</servlet-name>

<servlet-class>KaptchaServlet</servlet-class>

</servlet>

Copy after login

The above is the method introduced by the editor to use open source tools to create web page verification codes. , I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more related articles on how to use open source tools to create web page verification codes, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles