基于ssm实现验证码功能
3、验证码
- 使用现成的依赖生成验证码
- web.xml配置生成验证码的参数及url-pattern
3.1 导入依赖
<!-- 验证码依赖 -->
<!-- Kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2 web.xml 配置Servlet
<servlet>
<servlet-name>cap</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</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.char.string</param-name>
<param-value>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>211,229,237</param-value>
</init-param>
<init-param>
<!-- session.setAttribute("captcha","验证码") -->
<param-name>kaptcha.session.key</param-name>
<param-value>captcha</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>cap</servlet-name>
<!-- 请求如下地址,就能获取一个验证码图片 -->
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
3.3 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="regist" method="post">
验证码:<input type="text" name="validateCode"/><img src="captcha" onclick="changeCode(this);"/>
<input type="submit" value="注册"/>
</form>
</body>
<script>
function changeCode(obj) {
obj.src = "captcha?time="+new Date().getTime();
}
</script>
</html>