开发生成图形验证码接口
图片实体 ImageCode
public class ImageCode {
/**
* 一个图片验证码包含三个信息
*/
private BufferedImage image; //图片
private String code;//code是一个随机数,图片根据这个随机数生成,这个随机数是要存入到session中的
private LocalDateTime expireTime;//验证码图片过期时间
/**
*
* @param image
* @param code
* @param expireIn 多少秒过期
*/
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
}
public boolean isExpried() {
return LocalDateTime.now().isAfter(expireTime);
}
图片接口 ValidateCodeController
根据随机数生成图片
将随机数存到session中
将生成的图片写到接口的响应中
@RestController
public class ValidateCodeController implements Serializable {
private static final String SESSION_KEY ="SESSION_KEY_IMAGE_CODE";//key
//spring 操作session的工具类
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@RequestMapping("/code/image")
private void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//1根据请求中的随机数生成图片
ImageCode imageCode = createImageCode(request);
//2将随机数放到session中
sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
//3将生成的图片写到接口的响应中
ImageIO.write(imageCode.getImage(),"jpeg",response.getOutputStream());
}
private ImageCode createImageCode(HttpServletRequest request) {
//生成一个图片对象
int width = 67;
int height =23;
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, 20));
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 <4; 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, 16);
}
g.dispose();
return new ImageCode(image, sRand, 60);
}
在认证流程中加入图形验证码校验
登录页面
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>