简单模型
优势
开源、免费、简单、图片类型验证码
SpringMVC(SSM)配置
1、首先是配置jar包 如果你是Maven管理直接配置pom.xml文件即可.
<dependency>
<groupId>com.google.code.kaptcha</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
如果不是需要下载下jar包
下载地址:
2、配置Spring的配置文件web.xml文件中contextConfigLocation指向的文件
这里主要是配置验证码图片的样式和验证内容
<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.image.width">110</prop>
<!-- 验证码高度 -->
<prop key="kaptcha.image.height">50</prop>
<!-- 生成验证码内容范围 -->
<prop key="kaptcha.textproducer.char.string">123456789abcDeFGHjkLmnoQqrsTUVWXYZ</prop>
<!-- 验证码个数 -->
<prop key="kaptcha.textproducer.char.length">4</prop>
<!-- 是否有边框 -->
<prop key="kaptcha.border">no</prop>
<!-- 边框颜色 -->
<prop key="kaptcha.border.color">105,179,90</prop>
<!-- 边框厚度 -->
<prop key="kaptcha.border.thickness">1</prop>
<!-- 验证码字体颜色 -->
<prop key="kaptcha.textproducer.font.color">black</prop>
<!-- 验证码字体大小 -->
<prop key="kaptcha.textproducer.font.size">30</prop>
<!-- 验证码所属字体样式 -->
<prop key="kaptcha.textproducer.font.names">楷体</prop>
<!-- 干扰线颜色 -->
<prop key="kaptcha.noise.color">black</prop>
<!-- 验证码文本字符间距 -->
<prop key="kaptcha.textproducer.char.space">3</prop>
<!-- 图片样式 :阴影-->
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
3、jsp、js及java文件参考
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- 项目路径 -->
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path;
%>
<c:set var="base" value="<%=basePath%>" scope="application"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="resources/js/common/jquery.min.js"></script>
<script type="text/javascript" src="resources/js/common/jquery.md5.js"></script>
<script type="text/javascript" src="resources/js/login.js"></script>
<title>验证码</title>
</head>
<body>
<div>
<div>
<span id="message" style="color: red;"></span>
</div>
<form id="form" action="" method="post">
<div style="height:40px;">
<label>帐 号:</label>
<input name="userName" type="text" id="userName" value="" placeholder="用户名" maxlength="32"/>
</div>
<div style="height:16px;">
<label>密 码:</label>
<input type="password" id="password" name="password" value="" placeholder="密码" maxlength="16"/>
</div>
<div style="height:40px;">
<label>验证码:</label>
<input id="imageContent" name="imageContent" type="text" placeholder="验证码" maxlength="4" style="width: 71px;">
<img id="imgObj" alt="验证码" src="${base }/captcha/getCaptchaImage.do" οnclick="changeImg()">
<input id="timestamp" name="timestamp" value="${timestamp }" type="hidden" >
</div>
<img id="imgObj111" alt="验证码111" src="resources\images\duihao.png"style="margin-top: -2px;margin-left: 120px; display:none;">
<div style="height:40px;">
<input type="button" value="确定" style="margin-top: 20px;" οnclick="clickeBut()"/>
<input type="button" value="确定1" style="margin-top: 20px;" οnclick="clickeBut2()"/>
</div>
</form>
</div>
</body>
</html>
$(document).ready(function(){
// $("#clicke").click(function(){
// clickeBut();
// });
});
/**
* 更换图片
*/
function changeImg() {
var imgSrc = $("#imgObj");
var src = imgSrc.attr("src");
imgSrc.attr("src", chgUrl(src));
};
/**
* 时间戳
* 为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
*/
function chgUrl(url) {
var timestamp = (new Date()).valueOf();
var stamp = $("#timestamp");
// alert(url);
url = url.substring(0, 60);
if ((url.indexOf("&") >= 0)) {
url = url + "×tamp=" + timestamp;
} else {
url = url + "?timestamp=" + timestamp;
stamp.val(timestamp);
}
return url;
};
/**
* 提交
*/
function clickeBut(){
//帐号
var userName = $("#userName").val().trim();
//密码
var password = $("#password").val().trim();
//验证码
var imageContent = $("#imageContent").val().trim();
if(userName.length == 0){
$("#message").text("请输入帐号");
return false;
}
// console.log(password);
if(password.length == 0){
$("#message").text("请输入密码");
return false;
}
if(imageContent.length == 0){
$("#message").text("请输入验证码");
return false;
}else if(imageContent.length < 4){
$("#message").text("验证码错误");
return false;
}else{
//密码判断
$.ajax({
type : 'post',
url : 'longin.htm',
data : {
"userName" : userName,
"password" : $.md5(password)
},
success : function(data) {
//'0'失败,'1'成功
if(data==0){
$("#message").text("账号或密码错误");
return false;
}else if(checkImageCode(imageContent)){
//成功提交
$("#form").attr("action", "index.htm");
$("#form").submit();
}
}
});
}
};
/**
* 验证码校验
*/
function checkImageCode(s) {
//验证码
var code = s.trim();
var timestamp = $("#timestamp").val().trim();
// console.log(code + " " + timestamp);
var status = "";
var boo=false;
if(code.length != 0 ){
$.ajax({
type : 'post',
async : false,
url : 'captcha/checkCaptcha.do',
data : {
"code" : code
},
success : function(data) {
status = data;
}
});
if(status.indexOf("true")>=0){
document.getElementById("imgObj111").style.display = "block";
$("#imagCheck").val("true");
$("#message").text("");
boo = true;
}else{
changeImg();
document.getElementById("imgObj111").style.display = "none";
$("#message").text("验证码错误");
return false;
}
}else{
$("#message").text("请输入验证码");
return;
}
return boo;
// console.log(status);
}
package com.controller;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
/**
* 验证码相关的接口
*
* @author gaowei.cheng
*/
@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController {
private static final Log log = LogFactory.getLog(CaptchaController.class);
@Autowired
private Producer captchaProducer;
/**
* 页面入口
* @param model
* @return
*/
@RequestMapping(value = "/getCaptcha.do", method = RequestMethod.GET)
public String getCaptcha(Model model) {
model.addAttribute("timestamp", System.currentTimeMillis());
return "captcha";
}
/**
* 生成带验证码的图片
* @param model
* @param request
* @param response
* @param timestamp
* @return
* @throws IOException
*/
@RequestMapping(value = "/getCaptchaImage.do", method = RequestMethod.GET)
public ModelAndView getCaptchaImage(Model model,HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "timestamp", required = false) String timestamp) throws IOException {
if (StringUtils.isEmpty(timestamp)) {
//System.out.println("没有时间戳\ttimestamp:" + timestamp);
model.addAttribute("timestamp", System.currentTimeMillis());
} else {
//System.out.println("有时间戳\ttimestamp:" + timestamp);
model.addAttribute("timestamp", timestamp);
}
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();
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
log.info("======生成了一个验证码,内容为:" + capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
}
/**
*
* @param timestamp
* @param code
* @param request
* @return true或fasle,ture表示验证成功,false表示验证失败
*/
@RequestMapping(value = "/checkCaptcha.do", method = RequestMethod.POST)
@ResponseBody
public String checkCaptcha(@RequestParam(value = "timestamp", required = false) String timestamp, @RequestParam(value = "code", required = false) String code,HttpServletRequest request) {
boolean returnStr = false;
String original =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
log.info("======用户输入的验证码:" + code);
log.info("======正确的验证码:" + original);
if (!StringUtils.isEmpty(code)) {
if (code.equalsIgnoreCase(original)) {
returnStr = true;
}
}
log.info("======验证结果" + returnStr);
return returnStr + "";
}
}
CaptchaImageCreateController.java
package com.controller;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
@Controller
@RequestMapping("/")
public class CaptchaImageCreateController {
private Producer captchaProducer = null;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
@RequestMapping("/captcha-image")
public ModelAndView handleRequest
(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
}
}
到此整个一个简单的登陆验证完成,代码仅供参考。
复制粘贴不可怕,可怕的是复制粘贴代码从不用脑研究。自己会的东西才是自己的
验证码样式
Constant | 描述 | 默认值 |
kaptcha.border | 图片边框,合法值:yes , no | yes |
kaptcha.border.color | 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. | black |
kaptcha.border.thickness | 边框厚度,合法值:>0 | 1 |
kaptcha.image.width | 图片宽 | 200 |
kaptcha.image.height | 图片高 | 50 |
kaptcha.producer.impl | 图片实现类 | com.google.code.kaptcha.impl.DefaultKaptcha |
kaptcha.textproducer.impl | 文本实现类 | com.google.code.kaptcha.text.impl.DefaultTextCreator |
kaptcha.textproducer.char.string | 文本集合,验证码值从此集合中获取 | abcde2345678gfynmnpwx |
kaptcha.textproducer.char.length | 验证码长度 | 5 |
kaptcha.textproducer.font.names | 字体 | Arial, Courier |
kaptcha.textproducer.font.size | 字体大小 | 40px. |
kaptcha.textproducer.font.color | 字体颜色,合法值: r,g,b 或者 white,black,blue. | black |
kaptcha.textproducer.char.space | 文字间隔 | 2 |
kaptcha.noise.impl | 干扰实现类 | com.google.code.kaptcha.impl.DefaultNoise |
kaptcha.noise.color | 干扰颜色,合法值: r,g,b 或者 white,black,blue. | black |
kaptcha.obscurificator.impl | 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy | com.google.code.kaptcha.impl.WaterRipple |
kaptcha.background.impl | 背景实现类 | com.google.code.kaptcha.impl.DefaultBackground |
kaptcha.background.clear.from | 背景颜色渐变,开始颜色 | light grey |
kaptcha.background.clear.to | 背景颜色渐变,结束颜色 | white |
kaptcha.word.impl | 文字渲染器 | com.google.code.kaptcha.text.impl.DefaultWordRenderer |
kaptcha.session.key | session key | KAPTCHA_SESSION_KEY |
kaptcha.session.date | session date | KAPTCHA_SESSION_DATE |