privatestaticfinalint VERIFY_CODE_HEIGHT =25;//验证码高度privatestaticfinalint VERIFY_CODE_WIDTH =70;//验证码宽度privatestaticfinalchar[] codeSequence ={'0','1','2','3','4','5','6','7','8','9'};/**
* 获取验证码
* @param req 请求
* @param res 响应
* @throws IOException
*/@GetMapping("verificationCode")publicvoidverificationCode(HttpServletRequest req,HttpServletResponse res)throwsIOException{BufferedImage image =newBufferedImage(VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT,BufferedImage.TYPE_INT_RGB);//获取图片上下文Graphics graphics = image.getGraphics();//生成随机类Random random =newRandom();//设置背景色
graphics.setColor(getRandColor(200,250));
graphics.fillRect(0,0, VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT);// 设定字体
graphics.setFont(newFont("Times New Roman",Font.PLAIN,18));// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
graphics.setColor(getRandColor(160,200));for(int i =0; i <160; i++){int x = random.nextInt(VERIFY_CODE_WIDTH);int y = random.nextInt(VERIFY_CODE_HEIGHT);int xl = random.nextInt(12);int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);}// 取随机产生的认证码(4位数字)String sRand ="";for(int i =0; i <4; i++){String rand =String.valueOf(codeSequence[random.nextInt(10)]);
sRand += rand;// 将认证码显示到图象中
graphics.setColor(newColor(20+ random.nextInt(110),20+ random
.nextInt(110),20+ random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
graphics.drawString(rand,13* i +10,20);}// 图象生效
graphics.dispose();// 输出图象到页面//将VerifyCode绑定session(VerifyCode 可根据实际情况自行定义)
req.getSession().setAttribute("VerifyCode", sRand);//设置响应头
res.setHeader("Pragma","no-cache");//设置响应头
res.setHeader("Cache-Control","no-cache");//在代理服务器端防止缓冲
res.setDateHeader("Expires",0);//设置响应内容类型
res.setContentType("image/jpeg");ByteArrayOutputStream out =newByteArrayOutputStream();ImageIO.write(image,"JPEG", out);
res.setContentLength(out.size());
res.getOutputStream().write(out.toByteArray());
res.getOutputStream().flush();}
设置背景色
/**
* 设置背景色
* @param i
* @param j
* @return
*/privatestaticColorgetRandColor(int i,int j){Random random =newRandom();if(i >255)
i =255;if(j >255)
j =255;int r = i + random.nextInt(j - i);int g = i + random.nextInt(j - i);int b = i + random.nextInt(j - i);returnnewColor(r, g, b);}