利用Kaptch
在服务端内存中画出验证码:
步骤
1 导入jar包
2 编写kaptch 配置类
3 生成随机字符,生成图片
在pom.xml 文件中导入
com.github.penggle kaptcha 2.3.2
新建配置类
因为springboot 针对他没有做自动配置 新建一个配置类
(config/ kaptchaConfig)
1 做@configuration 配置注解标注
@Bean 让其被spring 容器管理
要装配kaptcha 核心对象类
producer (实例化接口)
package com.nowcoder.community.config;
import com.google.code.kaptcha.Producer;
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 Producer kaptchaProduct(){
//实例化她的实现类
Properties properties=new Properties();
properties.setProperty("kaptcha.image.width","100");
properties.setProperty("kaptcha.image.height","40");
properties.setProperty("kaptcha.textproducer.font.size","32");
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
properties.setProperty("kaptcha.textproducer.char.string","0987654321QWERTYUIOPL");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptchat= new DefaultKaptcha();
Config config=new Config(properties);
kaptchat.setConfig(config);
return kaptchat;
}
}
2 生成验证码的方法 在controller 里
不写在login 方法里因为 返回的是html 页面
所以要单独写一个请求返回图片。
//生成验证码
@RequestMapping(path="/kaptcha",method=RequestMethod.GET)
public void getKaptcha (HttpServletResponse response, HttpSession session){
//生成验证码
String text=kaptchaProducer.createText();
BufferedImage image=kaptchaProducer.createImage(text);
//将验证码存入session
session.setAttribute("keptcha",text);
//将图片输出给浏览器
response.setContentType("image/png");
try{
OutputStream os=response.getOutputStream();
ImageIO.write(image,"png",os);
}catch (IOException e){
logger.error("响应验证码失败"+e.getMessage());
e.printStackTrace();}
}
}
3 修改login.html 将图片改为动态的
设置更新的方法:
tips:
在global.js 里将访问路径的/community 存为全局变量 方便如果更改的时候方便更改不要写死
加random 是因为防止不刷新
图片是个静态资源有的浏览器会认为他没有变化 所以欺骗一下他浏览器觉得他变了
刷新验证码



