一、说明
该文章是从小白出发,通过java实现图像验证码的生成与显示,进一步实现动态切换,从而实现登陆界面和注册界面的优化。
二、效果图
什么都不说,先上效果图:
三、具体代码实现
(1)新建类“KaptchaConfig”,添加的内容如下:
@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");
Config config=new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
(2)有红色就按它提示添加依赖包就行,一般可能是“ALT+ENTER”快捷键,操作时建议确保联网,我添加的包后,类“KaptchaConfig.java”的完整代码如下:
package com.example.demo; //这个是你新建类的时候就有的,每个人不一样
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");
Config config=new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
(3)接下来就是在控制层实现图像验证码生成与映射:
@Autowired
private Producer producer;
@RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response,HttpServletRequest request) throws IOException {
response.setHeader("Cache-Control","no-store,no-cache");
response.setContentType("image/jpeg");
String text = producer.createText();
BufferedImage image = producer.createImage(text);
HttpSession session = request.getSession();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
session.setMaxInactiveInterval(60);
ServletOutputStream out;
out = response.getOutputStream();
ImageIO.write(image,"jpg",out);
}
(4)前端验证码显示:
<div>
<input type="text" name="canver" id="canver" placeholder="验证码">
< img id="imgs" name="imgs" src="../captcha.jpg" width="80" height="46" οnclick="fun1()" >
</div>
(5)前端图像验证码的动态刷新:
<script type="text/javascript">
function fun1(){
var p=document.getElementById("imgs");
p.src="../captcha.jpg";
}
</script>
四、任务完成
恭喜你,到此你就能成功生成图像验证码,显示和动态刷新了