com.github.axet
kaptcha
0.0.9
第二步:配置KaptchaConfig(验证码图像的一些配置信息)
package com.example.demo.kaptcha;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
Properties properties = new Properties();
// 图片边框
properties.setProperty("kaptcha.border", "no");
// 边框颜色
properties.setProperty("kaptcha.border.color", "black");
//边框厚度
properties.setProperty("kaptcha.border.thickness", "1");
// 图片宽
properties.setProperty("kaptcha.image.width", "200");
// 图片高
properties.setProperty("kaptcha.image.height", "50");
//图片实现类
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
//文本实现类
properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
//文本集合,验证码值从此集合中获取
properties.setProperty("kaptcha.textproducer.char.string", "01234567890qwertyuiopasdfghjklzxcvbnm");
//验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
//字体
properties.setProperty("kaptcha.textproducer.font.names", "宋体");
//字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "black");
//文字间隔
properties.setProperty("kaptcha.textproducer.char.space", "5");
//干扰实现类
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
//干扰颜色
properties.setProperty("kaptcha.noise.color", "blue");
//干扰图片样式
properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
//背景实现类
properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
//背景颜色渐变,结束颜色
properties.setProperty("kaptcha.background.clear.to", "white");
//文字渲染器
properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
第三步:生成验证码图像的CaptchaController
package com.example.demo.kaptcha;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@Controller
public class CaptchaController {
@Autowired
private Producer captchaProducer;
@Autowired
private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);
@RequestMapping("getimg")
public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
logger.debug("******************验证码是: " + code + "******************");
response.setDateHeader("Expires", 0);
// 设置标准的HTTP/1.1无缓存头信息
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// 设置IE扩展的HTTP/1.1无缓存头(使用addHeader)
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// 设置标准HTTP/1.0无缓存报头
response.setHeader("Pragma", "no-cache");
// 返回一个jpeg
response.setContentType("image/jpeg");
// 为图像创建文本
String capText = captchaProducer.createText();
// 将文本存储在会话中
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// 用文本创建图像
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// 导出数据
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
}
}
上面代码看不懂的,去学学IO流!
第四步:后台登录Controllerpackage com.example.demo.kaptcha;
import com.google.code.kaptcha.Constants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class login {
@GetMapping("login")
public boolean login(HttpServletRequest request, @RequestParam("code") String code) {
String sessionCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
if (code.equals(sessionCode)) {
// 验证正常返回true
return true;
} else {
// 验证失败返回false
return false;
}
}
}
第五步:跨域配置webconfig
在demo下创建一个config包添加一个webconfig文件
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlbasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class webconfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
corsConfiguration.setAllowCredentials(true);//支持安全证书。跨域携带cookie需要配置这个
corsConfiguration.setMaxAge(3600L);//预检请求的有效期,单位为秒。设置maxage,可以避免每次都发出预检请求
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlbasedCorsConfigurationSource source = new UrlbasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
第六步:测试
运行项目:
1、获得图片
在浏览器中输入:http://localhost:8080/getimg
2、验证校验码在浏览器中输入:http://localhost:8080/login?code=m83v
假如错误
前端 第一步:创建一个network包。并编写封装import axios from 'axios'
// 运行跨域携带cookie
axios.defaults.withCredentials = true
export function kaptcha(config) {
let newVar = axios.create({
baseURL: 'http://localhost:8080',
timeout:5000
});
return newVar(config);
}
第二步,编写页面
我就在vue原有的helloworld.vue的页面上改,删除里面原有的div。
图像验证码
判断结果:{{this.$data.message}}
第三步,测试
正确返回true
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XslpgDpc-1644230852718)(C:UsersxinjiAppDataRoamingTyporatypora-user-imagesimage-20220207184548616.png)]
错误返回false
本片注意,跨域问题!!!



