隐藏地址+图形验证码
目的
这么做主要是为了防止客户端提前拿到接口地址,在秒杀开始的时候直接调用秒杀接口。
思路
本次实验做法:/getPath获取秒杀链接,之后访问新链接进行秒杀。getPath中要验证图形验证码的结果是否正确。
本次实验缺点:因为真正的秒杀地址为/miaosha+{/getPath获取的data},仍然可以通过get请求获得真正秒杀地址。
更好的做法:调用/getPath接口可以返回一个页面的url,让浏览器跳转到这个新的url页面,新的页面才是真正的秒杀页面。
实现
获取图形验证码图片请求
@RequestMapping(value="/verifyCode", method=RequestMethod.GET)
@ResponseBody
public Result<String> getMiaoshaVerifyCod(HttpServletResponse response,MiaoshaUser user,
@RequestParam("goodsId")long goodsId) {
if(user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
try {
BufferedImage image = miaoshaService.createVerifyCode(user, goodsId);
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
return Result.success("获取验证码成功");
}catch(Exception e) {
e.printStackTrace();
return Result.error(CodeMsg.MIAOSHA_FAIL);
}
}
图片生成,把图片运算结果存入redis。
public BufferedImage createVerifyCode(MiaoshaUser user, long goodsId) {
if(user == null || goodsId <=0) {
return null;
}
int width = 80;
int height = 32;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //该图像具有整数像素的 8 位 RGB 颜色
Graphics g = image.getGraphics();
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
Random rdm = new Random();
for (int i = 0; i < 50; i+