前台代码
<div class="sign-in">
<input type="text" autocomplete="off" name="authCode" id="authCode" maxlength="6" class="ipt ipt_txt" placeholder="请输入验证码"/>
<!-- 验证码 -->
<div class="img-code"><img src="verifyCode.do" alt="" onclick="this.src=this.src+'?time='+new Date();"/></div>
</div>
public class StrUtils {
/**
* <pre>
* 获取N位随机数
* @param length
* @return
* </pre>
*/
public static String getRandom(int length) {
Random random = new Random();
String result="";
for(int i=0; i<length; i++){
result+=random.nextInt(10);
}
return result;
}
/**
* <pre>
* 获取验证码工具类
* patchca 是一个简单但功能强大的验证码的Java类库
* @author assassin
* @date 2017.6.2
* </pre>
*/
public class VerifyCode {
private ConfigurableCaptchaService captchaService = new ConfigurableCaptchaService();
private ThreadLocal<String> captchaLocal = new ThreadLocal<String>();
//初始化及配置验证码参数
public VerifyCode(String code) {
this.captchaLocal.set(code);
//
this.captchaService.setBackgroundFactory(new SingleColorBackgroundFactory(Color.WHITE));
this.captchaService.setColorFactory(new SingleColorFactory(Color.BLUE));
this.captchaService.setFilterFactory(new WobbleRippleFilterFactory());
this.captchaService.setWidth(90);
this.captchaService.setHeight(28);
this.captchaService.setFontFactory(new RandomFontFactory(20, new String[] { "Thoma", "Serif" }));
this.captchaService.setWordFactory(new WordFactory() {
public String getNextWord() {
return captchaLocal.get();
}
});
}
//获取验证码图片流
public BufferedImage getImage() {
return this.captchaService.getCaptcha().getImage();
}
//输出图片
public static void output(BufferedImage image, OutputStream out)
throws IOException {
ImageIO.write(image, "png", out);
}
}
控制器的编写
//生成验证码
@RequestMapping("/verifyCode")
public void verifyCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
//获取4个随机数
String code = StrUtils.getRandom(4);
VerifyCode verifyCode = new VerifyCode(code);
//获取图片
BufferedImage bufferedImage = verifyCode.getImage();
//把四个随机数放入到session中去
request.getSession().setAttribute("code", code);
//输出图片给客户端
VerifyCode.output(bufferedImage, response.getOutputStream());
}