Google kaptcha验证码在SpringMVC中的应用


1,下载kaptcha

https://code.google.com/archive/p/kaptcha/downloads

2,导入到Maven仓库

mvn install:install-file -Dfile=c:/kaptcha-2.3.2.jar -DgroupId=com.google.code.kaptcha -DartifactId=kaptcha -Dversion=2.3.2 -Dpackaging=jar

 

3,配置pom.xml依赖项

<dependency>
<groupId>com.google.code.kaptcha</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>

 

4,在Springmvc-Servlet.xml中配置bean

<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.border">yes</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.textproducer.font.color">blue</prop>
<prop key="kaptcha.image.width">125</prop>
<prop key="kaptcha.image.height">45</prop>
<prop key="kaptcha.textproducer.font.size">45</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">Microsoft YaHei,SimSun,SimHei</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>

 

5,测试代码

@RequestMapping("/kaptcha")
public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {

HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}

}

 

参考:

https://www.cnblogs.com/moonlightL/p/7282469.html

参数详解:https://www.cnblogs.com/louis80/p/5230507.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注