1.拉入图形验证码得porm
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.在你的springMvc得配置文件配置好谷歌验证码得bean
<bean id="captchaProducer"
class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.border">no</prop>
<prop key="kaptcha.textproducer.font.size">45</prop>
<prop key="kaptcha.textproducer.font.color">gray</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
3 .写一个controller(注意包扫描),因为是前后端分离,所以不能使用session得方法,所以将验证码得值存到redis中共享
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;//用此将验证码转成字节传给前端
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.code.kaptcha.Producer;
@Controller
public class CaptchaImageCreateController {
private Producer captchaProducer = null;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
@Resource
private RedisTemplate<String, String> redis;//注入redis
@GetMapping("/kcode")
@ResponseBody
public Map<String, String> handleRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
//生成验证码得值
String capText = captchaProducer.createText();
//生成验证码得键
String token = UUID.randomUUID().toString();
// 存入redis
redis.opsForValue().set(token, capText, 5, TimeUnit.MINUTES);
response.setHeader("code_token", token);
BufferedImage bi = captchaProducer.createImage(capText);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
//放到map返回给前端展示
HashMap<String, String> map = new HashMap<String, String>();
map.put("code_token", token);
map.put("img", Base64.encodeBase64String(out.toByteArray()));//将图片转成BASE64编码字节
return map;
}
}
4.注意,这里返回前端的是转成base64的图片,前端需要这样显示:
<img src="data:image/png;base64,此处填base64编码"/>