使用Kaptcha 生成验证码十分简单并且参数可以进行自定义,以下简单记录下使用步骤。

石阡ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
1.在pom.xml中添加maven依赖:
com.google.code.kaptcha kaptcha 2.3 jdk15
2.web.xml中配置kaptcha属性:
yes 105,179,90 1 blue 150 50 verifyCode 4 4 30 blue
其中bean节点的id值 verifyCodeProducer 为在类中引用@Resource生成实例时的名称;属性配置中 kaptcha.session.key 的值为在session中存取名称。
在servlet节点中配置
3.controller类中的相关方法:
@Controller
public class CommonController {
@Autowired
private Producer verifyCodeProducer;
@RequestMapping(path = "/getVerifyCodeImage", method = RequestMethod.GET)
public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
ResponseUtils.noCache(response);
response.setContentType("image/jpeg");
String capText = verifyCodeProducer.createText();
session.setAttribute(Constants.SESSION_KEY_VERIFY_CODE, capText);
BufferedImage bi = verifyCodeProducer.createImage(capText);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.flush();
} catch (Exception ex) {
LOGGER.error("Failed to produce the verify code image: ", ex);
throw new ServerInternalException("Cannot produce the verify code image.");
} finally {
IOUtils.closeQuietly(out);
}
}
}
Constants.SESSION_KEY_VERIFY_CODE为属性配置中 kaptcha.session.key 的值。
4.jsp:
function changeVerifyCode() {
$('#verifyCodeImage').hide().attr('src', '${pageContext.request.contextPath}/getVerifyCodeImage?' + Math.floor(Math.random()*100) ).fadeIn();
event.cancelBubble=true;
}
5.kaptcha属性说明:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。