使用kaptcha验证码组件操作演示

1、创建一个Maven项目

使用kaptcha验证码组件操作演示

2、在pom.xml中引入相关依赖

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>com.wisezone</groupId>
 5   <artifactId>wdh_kaptcha</artifactId>
 6   <packaging>war</packaging>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <name>wdh_kaptcha Maven Webapp</name>
 9   <url>http://maven.apache.org</url>
10   
11    <properties>
12     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
13       <!-- 定义spring的版本变量在dependency里面直接引用 -->
14     <spring.version>4.3.2.RELEASE</spring.version>
15     <slf4j.version>1.7.2</slf4j.version>
16   </properties>
17   
18   <dependencies>
19         <!-- spring mvc -->
20         <dependency>
21             <groupId>org.springframework</groupId>
22             <artifactId>spring-webmvc</artifactId>
23             <version>${spring.version}</version>
24         </dependency>
25         <!-- web开发要有servlet -->
26         <dependency>
27             <groupId>javax.servlet</groupId>
28             <artifactId>javax.servlet-api</artifactId>
29             <version>3.0.1</version>
30         </dependency>
31 
32         <!-- 日志打印相关的jar -->
33         <dependency>
34             <groupId>org.slf4j</groupId>
35             <artifactId>slf4j-log4j12</artifactId>
36             <version>${slf4j.version}</version>
37         </dependency>
38         <dependency>
39             <groupId>org.slf4j</groupId>
40             <artifactId>slf4j-api</artifactId>
41             <version>${slf4j.version}</version>
42         </dependency>
43 
44         <!-- 验证码的生成 -->
45         <dependency>
46             <groupId>com.github.axet</groupId>
47             <artifactId>kaptcha</artifactId>
48             <version>0.0.9</version>
49         </dependency>
50   </dependencies>
51    <build>
52         <finalName>wdh_kaptcha</finalName>
53         <!-- 资源文件的设置 -->
54         <resources>
55             <resource>
56                 <directory>src/main/resources</directory>
57             </resource>
58             <resource>
59                 <directory>src/main/java</directory>
60                 <includes>
61                     <include>**/*.properties</include>
62                     <include>**/*.xml</include>
63                 </includes>
64                 <!-- 是否替换资源中的属性 -->
65                 <filtering>false</filtering>
66             </resource>
67         </resources>
68         <plugins>
69             <!-- compiler plugin -->
70             <plugin>
71                 <groupId>org.apache.maven.plugins</groupId>
72                 <artifactId>maven-compiler-plugin</artifactId>
73                 <version>2.3.2</version>
74                 <configuration>
75                     <source>1.7</source>
76                     <target>1.7</target>
77                     <encoding>UTF-8</encoding>
78                     <compilerArguments>
79                         <bootclasspath>${java.home}/lib/rt.jar</bootclasspath>
80                     </compilerArguments>
81                 </configuration>
82             </plugin>
83             <plugin>
84                 <groupId>org.eclipse.jetty</groupId>
85                 <artifactId>jetty-maven-plugin</artifactId>
86                 <version>9.2.1.v20140609</version>
87             </plugin>
88         </plugins>
89     </build>
90 </project>

3、启动WEB容器要在web.xml中配置前端控制器(DispatcherServlet)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="3.0"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 5   <servlet>
 6         <servlet-name>appServlet</servlet-name>
 7         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 8         <init-param>
 9             <param-name>contextConfigLocation</param-name>
10             <param-value>classpath:*.xml</param-value>
11         </init-param>
12         <!-- 表示启动容器时初始化该Servlet -->
13         <load-on-startup>1</load-on-startup>
14 
15     </servlet>
16     
17     <servlet-mapping>
18         <servlet-name>appServlet</servlet-name>
19         <!-- 这是拦截请求, /代表拦截所有请求, 也可以是.html或者.action这类的 -->
20         <url-pattern>/</url-pattern>
21     </servlet-mapping>
22     
23     <filter>
24         <filter-name>CharacterEncodingFilter</filter-name>
25         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
26         <init-param>
27             <param-name>encoding</param-name>
28             <param-value>UTF-8</param-value>
29         </init-param>
30     </filter>
31     <filter-mapping>
32         <filter-name>CharacterEncodingFilter</filter-name>
33         <url-pattern>/*</url-pattern>
34     </filter-mapping>
35 </web-app>

4、src/main/resources中配置相关信息

a、log4j.properties

 1 log4j.rootLogger=DEBUG, Console  
 2   
 3 #Console  
 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender  
 5 log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
 6 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
 7  
 8 log4j.logger.java.sql.ResultSet=INFO  
 9 log4j.logger.org.apache=INFO  
10 log4j.logger.java.sql.Connection=DEBUG  
11 log4j.logger.java.sql.Statement=DEBUG  
12 log4j.logger.java.sql.PreparedStatement=DEBUG 

b、servlet-context.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xsi:schemaLocation=" 
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 9         
10     <!-- 扫描package方便注解依赖注入-->
11     <context:component-scan base-package="com.wisezone" />
12 
13     <!--图片验证码配置 -->
14     <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
15         <property name="config">
16             <bean class="com.google.code.kaptcha.util.Config">
17                 <constructor-arg>
18                     <props>
19                         <prop key="kaptcha.border">yes</prop><!--是否有边框 -->
20                         <prop key="kaptcha.border.color">105,179,90</prop><!--设置边框颜色 -->
21                         <prop key="kaptcha.textproducer.font.color">green</prop><!--验证码文本字符颜色 默认为Color.BLACK -->
22                         <prop key="kaptcha.session.key">code</prop><!--验证码 -->
23                         <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop><!--设置字体样式 -->
24                         <prop key="kaptcha.border.thickness"></prop><!--边框粗细度 默认为1 -->
25                         <prop key="kaptcha.producer.impl"></prop><!--验证码生成器 默认为DefaultKaptcha -->
26                         <prop key="kaptcha.textproducer.impl"></prop><!-- 验证码文本生成器 默认为DefaultTextCreator -->
27                         <prop key="kaptcha.textproducer.char.string"></prop><!--验证码文本字符内容范围 默认为abcde2345678gfynmnpwx -->
28                         <prop key="kaptcha.textproducer.char.length">4</prop><!-- 验证码文本字符长度 默认为5 -->
29                         <prop key="kaptcha.textproducer.font.size">50</prop><!--验证码文本字符大小 默认为40 -->
30                         <prop key="kaptcha.textproducer.char.space">6</prop>    <!--验证码文本字符间距 默认为2 -->
31                         <prop key="kaptcha.image.width">200</prop>    <!--验证码图片宽度 默认为200 -->
32                         <prop key="kaptcha.image.height">60</prop> <!--验证码图片高度 默认为40 -->
33                     </props>
34                 </constructor-arg>
35             </bean>
36         </property>
37     </bean>
38     
39 
40 </beans>

5、Demo演示

KaptchaController.java

 1 package com.wisezone.kaptcha;
 2 
 3 import java.awt.image.BufferedImage;
 4 
 5 import javax.imageio.ImageIO;
 6 import javax.servlet.ServletOutputStream;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 
14 import com.google.code.kaptcha.Constants;
15 import com.google.code.kaptcha.Producer;
16 
17 
18 @Controller
19 @RequestMapping("kaptcha")
20 public class KaptchaController {
21 
22     @Autowired
23     private Producer captchaProducer;
24 
25     @RequestMapping("getKaptchaImage")
26     public void getKaptchaImage(HttpServletRequest request, 
27             HttpServletResponse response) throws Exception {
28 
29         response.setDateHeader("Expires", 0); 
30 
31         // Set standard HTTP/1.1 no-cache headers. 
32         response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
33         // Set IE extended HTTP/1.1 no-cache headers (use addHeader). 
34         response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
35         // Set standard HTTP/1.0 no-cache header. 
36         response.setHeader("Pragma", "no-cache");  
37         // return a jpeg 
38         response.setContentType("image/jpeg");  
39         // create the text for the image
40         String capText = captchaProducer.createText();  
41         // store the text in the session 
42         request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
43         // create the image with the text  
44         BufferedImage bi = captchaProducer.createImage(capText);  
45         ServletOutputStream out = response.getOutputStream();  
46         // write the data out  
47         ImageIO.write(bi, "jpg", out);  
48         try {  
49             out.flush();  
50         } finally {  
51             out.close();  
52         }  
53     }
54 }

6、启动容器查看结果:

使用kaptcha验证码组件操作演示

浏览器:http://localhost:8080/kaptcha/getKaptchaImage

使用kaptcha验证码组件操作演示