1.spring 配置文件 applicationContext.xml
2.Controller的实现
3.JSP页面代码
使用Jquery.validate方法来调用controller的方法进行验证
4.java验证代码
5.kaptcha可配置项
<!-- 登陆时验证码的配置 -->
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<!--通过构造函数注入属性值 -->
<constructor-arg type="java.util.Properties">
<props>
<!-- 验证码宽度 -->
<prop key="kaptcha.image.width">115</prop>
<!-- 验证码高度 -->
<prop key="kaptcha.image.height">46</prop>
<!-- 生成验证码内容范围 -->
<prop key="kaptcha.textproducer.char.string">abcde012345678gfynmnpwx</prop>
<!-- 验证码个数 -->
<prop key="kaptcha.textproducer.char.length">5</prop>
<!-- 是否有边框 -->
<prop key="kaptcha.border">no</prop>
<!-- 验证码字体颜色 -->
<prop key="kaptcha.textproducer.font.color">white</prop>
<!-- 验证码字体大小 -->
<prop key="kaptcha.textproducer.font.size">25</prop>
<!-- 验证码所属字体样式 -->
<prop key="kaptcha.textproducer.font.names">Arial, Courier</prop>
<prop key="kaptcha.background.clear.from">104,183,26</prop>
<prop key="kaptcha.background.clear.to">104,183,26</prop>
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
<!-- 干扰线颜色 -->
<prop key="kaptcha.noise.color">red</prop>
<!-- 验证码文本字符间距 -->
<prop key="kaptcha.textproducer.char.space">1</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
2.Controller的实现
package com.nis.web.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.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
public class CaptchaProducerController {
@Autowired
private Producer captchaProducer;
@RequestMapping("captcha-image")
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws IOException{
// Set to expire far in the past.
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.toUpperCase());
// 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;
}
}
3.JSP页面代码
<form id="loginForm" class="form-signin" action="${pageContext.request.contextPath }/login" method="post">
<div class="loginbox loginbox2">
<ul>
<li><input id="username" name="username" type="text" class="loginuser required" value="${username}" placeholder="请填写登录账号"/></li>
<li><input type="password" class="loginpwd required" id="password" name="password" placeholder="请填写登录密码"/></li>
<c:if test="${not empty isValidateCodeLogin and isValidateCodeLogin==true}">
<li class="yzm">
<span><input id="captcha" name="captcha" class="required" type="text" placeholder="验证码"/></span><cite><img alt="未获取验证码" src="${pageContext.request.contextPath}/captcha-image" id="captacha_image" class="mid"/></cite>
</li>
</c:if>
<li><input type="submit" class="loginbtn" value="登录"/>
<label><input id="rememberMe" name="rememberMe" ${rememberMe ? 'checked' : ''} type="checkbox" />记住我(公共场所慎用)</label>
</li>
</ul>
<div class="bottom">
<div id="messageBox" class="alert alert-error ${empty message ? 'hide' : ''}">
<label id="loginError" class="error">${message}</label>
</div>
</div>
</div>
</form>
使用Jquery.validate方法来调用controller的方法进行验证
$("#loginForm").validate({
rules: {
username: { required: true},
password: { required: true},
captcha: {remote: "${pageContext.request.contextPath}/validateCode"}//动态增加删除验证规则,访问validateCode进行验证
},
messages: {
username: {required: "请填写用户名..."},password: {required: "请填写密码..."},
captcha: {remote: "验证码不正确...", required: "请填写验证码..."}
},
errorLabelContainer: "#messageBox",//显示错误信息的容器
errorPlacement: function(error, element) {//显示位置及添加方式
error.appendTo($("#loginError").parent());
}
});
4.java验证代码
@RequestMapping(value="/validateCode")
public void validateCode(HttpServletRequest request, HttpServletResponse response,String captcha) {
renderString(response, UserUtils.validateCodeIsValid(captcha));
}
/**
* 验证码是否合法
* @param validateCode
* @return
*/
public static boolean validateCodeIsValid(String validateCode) {
String code = (String) getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
return (StringUtil.isBlank(validateCode) || validateCode.toUpperCase().equals(code));
}
/**
* 客户端返回JSON字符串
* @param response
* @param object
* @return
*/
protected String renderString(HttpServletResponse response, Object object) {
return renderString(response, JsonMapper.toJsonString(object), "application/json");
}
/**
* 客户端返回字符串
* @param response
* @param string
* @return
*/
protected String renderString(HttpServletResponse response, String string, String type) {
try {
response.reset();
response.setContentType(type);
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
return null;
} catch (IOException e) {
return null;
}
}
5.kaptcha可配置项
kaptcha.border 是否有边框 默认为true 我们可以自己设置yes,no
kaptcha.border.color 边框颜色 默认为Color.BLACK
kaptcha.border.thickness 边框粗细度 默认为1
kaptcha.producer.impl 验证码生成器 默认为DefaultKaptcha
kaptcha.textproducer.impl 验证码文本生成器 默认为DefaultTextCreator
kaptcha.textproducer.char.string 验证码文本字符内容范围 默认为abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码文本字符长度 默认为5
kaptcha.textproducer.font.names 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
kaptcha.textproducer.font.size 验证码文本字符大小 默认为40
kaptcha.textproducer.font.color 验证码文本字符颜色 默认为Color.BLACK
kaptcha.textproducer.char.space 验证码文本字符间距 默认为2
kaptcha.noise.impl 验证码噪点生成对象 默认为DefaultNoise
kaptcha.noise.color 验证码噪点颜色 默认为Color.BLACK
kaptcha.obscurificator.impl 验证码样式引擎 默认为WaterRipple
kaptcha.word.impl 验证码文本字符渲染 默认为DefaultWordRenderer
kaptcha.background.impl 验证码背景生成器 默认为DefaultBackground
kaptcha.background.clear.from 验证码背景颜色渐进 默认为Color.LIGHT_GRAY
kaptcha.background.clear.to 验证码背景颜色渐进 默认为Color.WHITE
kaptcha.image.width 验证码图片宽度 默认为200
kaptcha.image.height 验证码图片高度 默认为50