SSM框架下实现验证码图片验证功能
背景图片资源路径
https://download.csdn.net/download/hero_qhz/10322064
一、首先,在pom里面加上需要用的资源jar包等,并且加上验证图片的引用图片路径,否则项目启动会报找不到图片资源的错误
com.octo.captcha
jcaptcha
1.0
src/main/java
**/*.xml
src/main/resources
**/*.*
src/main/java/com/first/captcha
**/*.*
二、在spring-mybatis.xml下面配置验证码相关属性及工具类
三、在你的工具util包下面加入CaptchaEngine工具类
public class CaptchaEngine extends ListImageCaptchaEngine {
/** 图片宽度 */
private static final int IMAGE_WIDTH = 80;
/** 图片高度 */
private static final int IMAGE_HEIGHT = 28;
/** 最小字体大小 */
private static final int MIN_FONT_SIZE = 12;
/** 最大字体大小 */
private static final int MAX_FONT_SIZE = 16;
/** 最小字符个数 */
private static final int MIN_WORD_LENGTH = 4;
/** 最大字符个数 */
private static final int MAX_WORD_LENGTH = 4;
/** 随机字符 */
private static final String CHAR_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZSZHZOZPZXZXZ";
/** 随机背景图片路径 */
private static final String BACKGROUND_IMAGE_PATH = "/webapp/resources/captcha";
/**
* 随机字体
*/
private static final Font[] FONTS = new Font[] { new Font("nyala", Font.BOLD, MAX_FONT_SIZE), new Font("Arial", Font.BOLD, MAX_FONT_SIZE), new Font("nyala", Font.BOLD, MAX_FONT_SIZE), new Font("Bell", Font.BOLD, MAX_FONT_SIZE), new Font("Bell MT", Font.BOLD, MAX_FONT_SIZE), new Font("Credit", Font.BOLD, MAX_FONT_SIZE), new Font("valley", Font.BOLD, MAX_FONT_SIZE),
new Font("Impact", Font.BOLD, MAX_FONT_SIZE) };
/**
* 随机颜色
*/
private static final Color[] COLORS = new Color[] { new Color(255, 255, 255), new Color(255, 220, 220), new Color(220, 255, 255), new Color(220, 220, 255), new Color(255, 255, 220), new Color(220, 255, 220) };
/**
* 验证码图片生成
*/
@Override
protected void buildInitialFactories() {
FontGenerator fontGenerator = new RandomFontGenerator(MIN_FONT_SIZE, MAX_FONT_SIZE, FONTS);
// BackgroundGenerator backgroundGenerator = new FileReaderRandomBackgroundGenerator(IMAGE_WIDTH, IMAGE_HEIGHT, new ClassPathResource(BACKGROUND_IMAGE_PATH).getPath());
BackgroundGenerator backgroundGenerator = new FileReaderRandomBackgroundGenerator(IMAGE_WIDTH, IMAGE_HEIGHT, CaptchaBgImage.class.getResource("").getPath());
TextPaster textPaster = new DecoratedRandomTextPaster(MIN_WORD_LENGTH, MAX_WORD_LENGTH, new RandomListColorGenerator(COLORS), new TextDecorator[] {});
addFactory(new GimpyFactory(new RandomWordGenerator(CHAR_STRING), new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster)));
}
}
四、建一个空的class,该包下面就是这个class和验证码背景图片 图片资源可去下面下载
https://download.csdn.net/download/hero_qhz/10322064
package com.first.captcha;
public class CaptchaBgImage {
}
五、controller跳转至验证码页面
/**
* 首页登录页
* @return
*/
@RequestMapping("/lists")
public ModelAndView lists(ModelMap model){
model.addAttribute("captchaId", UUID.randomUUID().toString());
ModelAndView mv = new ModelAndView();
mv.setViewName("/lists");
return mv;
}
页面:
//刷新验证码
function changeCode(){
$("#captchaImage").attr("src", "${base}/user/captcha.do?captchaId=${captchaId}×tamp=" + (new Date()).valueOf());
}
captcha.do:
/**
* 验证码
*/
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (StringUtils.isEmpty(captchaId)) {
captchaId = request.getSession().getId();
}
String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse().toString();
String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse().toString();
response.addHeader(pragma, value);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream servletOutputStream = null;
try {
servletOutputStream = response.getOutputStream();
BufferedImage bufferedImage = captchaService.buildImage(captchaId);
ImageIO.write(bufferedImage, "jpg", servletOutputStream);
servletOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(servletOutputStream);
}
}
验证码验证是否正确时使用ajax验证:
$.ajax({
type:"post",
data:{userId: $id, phone: phone,captchaId : $captchaIds,captcha:$captchas},
dataType:'json',url:'${path}/member/safe/getCode.do',
var message = JSON.parse(data);
success:function(data){lui.closeLoding();if(message.type == "success"){
}else if(message.content == "验证码错误"){
time($sendPhone,60);lui.success(message.content);changeCodes();
lui.info(message.content);
lui.info(message.content);}else if(message.type == "error"){changeCodes();}},
});
error:function(message){lui.closeLoding();changeCodes();lui.fail('服务繁忙,请稍后再试');
}
controller方法:
@RequestMapping(value = "/getCode", method = RequestMethod.POST)
public @ResponseBody String getCode(String userId, String phone,String captchaId,String captcha) {
if (!captchaService.isValid(null,captchaId, captcha)) {
return message(Type.error, "验证码错误");
}
}
public String message(Type type ,String content){
return "{\"type\":\""+(type == Type.success ? "success" : "error")+"\",\"content\":\""+content+"\"}";
}
service:
public interface CaptchaService {
/**
* 生成验证码图片
*
* @param captchaId
* 验证ID
* @return 验证码图片
*/
BufferedImage buildImage(String captchaId);
/**
* 验证码验证
*
* @param captchaType
* 验证码类型
* @param captchaId
* 验证ID
* @param captcha
* 验证码(忽略大小写)
* @return 验证码验证是否通过
*/
boolean isValid(String captchaId, String captcha);
}
CaptchaServiceImpl:注意 @Resource(name="imageCaptchaService") 要和spring-mybatis.xml引用名称配置文件保存一致
@Service
public class CaptchaServiceImpl implements CaptchaService {
@Resource(name="imageCaptchaService")
private com.octo.captcha.service.CaptchaService imageCaptchaService;
public BufferedImage buildImage(String captchaId) {
return (BufferedImage) imageCaptchaService.getChallengeForID(captchaId);
}
@Override
public boolean isValid(String captchaId, String captcha) {
if (StringUtils.isNotEmpty(captchaId) && StringUtils.isNotEmpty(captcha)) {
try {
return imageCaptchaService.validateResponseForID(captchaId, captcha.toUpperCase());
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
}
这样就可以实现验证码图片及验证了。