利用Kaptcha包实现。
1. 引入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. 编写配置类,对Kaptcha进行配置
在com.nowcoder.mycommunity目录下新建config包,在该包下新建类:KaptchaConfig
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer(){
//起到配置文件的作用
//以前都是从配置文件里读取值,这里直接现场写
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", "0123456789abcdefghigklmnopqrstuvwxyz"); //生成字符串的范围
properties.setProperty("kaptcha.textproducer.char.length", "4"); //字符串的长度
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); //噪声类型
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3. 创建控制器方法,用来生成验证码
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private Producer kaptchaProducer;
//生成验证码
@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("kaptcha",text);
//用os字节流输出图片,发送给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
} catch (IOException e) {
logger.error("响应验证码失败:" + e.getMessage());
}
}
4. 登陆界面的html
刷新验证码按钮:
<div class="col-sm-4">
<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a>
</div>
刷新按钮对应的方法:
<script>
function refresh_kaptcha() {
var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
<!--#kaptcha为id,将其src属性改为path-->
$("#kaptcha").attr("src", path);
}
</script>
注:需要搜索global.js,将全局变量配置进去:var CONTEXT_PATH = "/COMMUNITY";