参考文章链接:https://www.cnblogs.com/zhangyuanbo/p/11214078.html
Kaptcha 简介
Kaptcha 是一个可高度配置的实用验证码生成工具
可以去官网http://code.google.com/p/kaptcha/下载jar,或者在pom.xml中导入

<dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>0.0.9</version>
</dependency>

1.配置类producer

package com.yxb.posadmin.common.config;import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.Properties;/*** 生成验证码配置*/
@Configuration
public class KaptchaConfig {@Beanpublic DefaultKaptcha producer() {Properties properties = new Properties();properties.put("kaptcha.border", "no");properties.put("kaptcha.textproducer.font.color", "black");properties.put("kaptcha.textproducer.char.space", "5");Config config = new Config(properties);DefaultKaptcha defaultKaptcha = new DefaultKaptcha();defaultKaptcha.setConfig(config);return defaultKaptcha;}
}

2.后台生成图片验证码

/*** 获取图片验证码* @param response* @param request* @throws ServletException* @throws IOException*/@RequestMapping("captcha")public void captcha(HttpServletResponse response, HttpServletRequest request)throws ServletException, IOException {response.setHeader("Cache-Control", "no-store, no-cache");response.setContentType("image/jpeg");//生成文字验证码String text = producer.createText();//生成图片验证码BufferedImage image = producer.createImage(text);//保存到sessionrequest.getSession().setAttribute(CommonConstant.ADMIN_KAPTCHA_SESSION_KEY, text);ServletOutputStream out = response.getOutputStream();ImageIO.write(image, "jpg", out);}

3.页面代码login.html

//定义的图片访问路径
data:{
src: 'login/captcha'
}
//页面<div class="form-group"><label class="sr-only" for="password">验证码</label><input type="text" class="form-control" maxlength="6" name="captcha"     @keyup.enter="sendVerificationCode(true)" id="captcha" placeholder="请输入验证码">
</div>
<div class="form-group  has-feedback"><img alt="如果看不清楚,请单击图片刷新!" height="40" class="pointer" :src="src" @click="refreshCode"><a href="javascript:;" @click="refreshCode">点击刷新</a>
</div>
//函数refreshCode: function(){this.src = "login/captcha?t=" + $.now();
},

4.后端接收代码

public ResultData<Object> doLogin(String username, String password, String captcha){
//session中的验证码
String kaptcha = (String) session.getAttribute(CommonConstant.ADMIN_KAPTCHA_SESSION_KEY);
//传过来的验证码和session中的不一样
if(!captcha.equals(kaptcha)){return resultData.initCodeAndDesp(2,"验证码不正确");
}
}