1.新建图形验证码属性类:
/**
* 图形验证码属性配置
*
* @author zhaohaibin
*/
@Data
public class ImageCodeProperties {
private int width = 68;
private int height = 32;
private int length = 4;
/**
* 有效期
*/
private int expireIn = 60;
}
2.验证码基础类(方便扩展短信验证码):
/**
* 验证码属性配置基础类
*
* @author zhaohaibin
*/
@Data
public class ValidateCodeProperties {
private ImageCodeProperties image = new ImageCodeProperties();
}
3.更新SecurityProperties:
/**
* security基础属性配置类
* @author zhaohaibin
*/
@Data
@ConfigurationProperties(prefix = "demo.security")
public class SecurityProperties {
private BrowserProperties browser = new BrowserProperties();
/**
* 验证码配置
*/
private ValidateCodeProperties code = new ValidateCodeProperties();
}
4.更新ValidateCodeController:
@Autowired
private SecurityProperties securityProperties;
/**
* 生成图形验证码
*
* @param request
* @return
*/
private ImageCode createImageCode(HttpServletRequest request) {
// 请求配置覆盖自定义配置覆盖默认配置
int width = ServletRequestUtils.getIntParameter(request, "width", securityProperties.getCode().getImage().getWidth());
int height = ServletRequestUtils.getIntParameter(request, "height", securityProperties.getCode().getImage().getHeight());
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 字体大小
g.setFont(new Font("Times New Roman", Font.ITALIC, 24));
g.setColor(getRandColor(160, 200));
// 随机线条
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
// 根据配置长度生成随机数
for (int i = 0; i < securityProperties.getCode().getImage().getLength(); i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
// 设置左、上边距
g.drawString(rand, 13 * i + 6, 26);
}
g.dispose();
return new ImageCode(image, sRand, 60);
}
4.配置启动,覆盖顺序->请求配置覆盖自定义配置覆盖默认配置:
# security 默认登录页面配置
demo:
security:
browser:
loginPage: "/demoLogin.html"
# loginType: "REDIRECT"
code:
image:
# 图形验证码长度
length: 6
# 图形验证码图形宽
width: 100
<div><label>验证码</label><input type="text" name="imageCode" placeholder="请输入验证码"/><img src="code/image?width=200" alt=""></div>
问题排查:
暂无