前言:今天想实现一个验证码功能,经过一番探索发现,只要img的src属性直接保存访问后端生成验证码方法的完整路径即可。 然后图片验证码能显示出来了。
后端准备工作:
<properties>
<java.version>1.8</java.version>
<kaptcha.version>0.0.9</kaptcha.version>
</properties>
<dependencies>
<!--引入图片验证码的依赖-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
前端:
<el-col :span="10" class="login-captcha">
<img :src="captchaPath" @click="getCaptcha()" alt="暂无图片" />
el-col>
this.captchaPath = `http://localhost:8083/api/captchaJpg
但是,事情没那么简单。问题来了,当我们点击图片验证码的时候发现,不会切换了,而且请求也不会发送到后端去。仔细思考,也是这么回事。当点击方法的时候,只是对变量进行字符串赋值。而且主要是每次往欲往后端发送的请求都是一样的。经过思考,角色是每次发送同样的请求的原因。于是我在请求加了个参数,为确保每次的请求路径不完全一样。采用uuid做为参数。
this.captchaPath = `http://localhost:8083/api/captchaJpg?uuid=${uuid}`;
uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = "-";
this.uuidA = s.join("");
console.log(s.join(""), 's.join("")');
return this.uuidA;
},
@GetMapping("/captchaJpg")
public void captcha(HttpServletResponse response,
@RequestParam("uuid") String uuid)throws IOException
{
System.out.println(uuid);
//生成文字验证码
String code = producer.createText();
// 获取图片验证码
BufferedImage image = producer.createImage(code);
System.out.println(image);
// 直接在浏览器页面进行显示
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
IOUtils.closeQuietly(out);
}
1.生成验证码配置类:KaptchaConfig
package com.example.upload.demo.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 {
@Bean
public 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");
properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
2.如果项目中有使用shiro,记得将验证码的请求放行