一、验证码效果
二、实现代码
VerifyCodeController.java
package com.xxl.sso.server.controller;
import com.xxl.sso.server.Util.JedisUtil;
import com.xxl.sso.server.Util.VerifyCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@Controller
@RequestMapping("/sso")
public class VerifyCodeController {
@RequestMapping("/getVerifyCode")
public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
try {
int width = 180;
int height = 60;
BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String randomText = VerifyCode.drawRandomText(width, height, verifyImg);
String sessionId = request.getSession().getId();
JedisUtil.setObjectValue(sessionId, randomText, 1 * 60);
System.out.println("获取验证码:" + randomText);
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(verifyImg, "png", os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
VerifyCode.java
package com.xxl.sso.server.Util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerifyCode {
public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();
graphics.setColor(new Color(30, 109, 201));
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
String baseNumLetter ="123456789";
StringBuffer sBuffer = new StringBuffer();
int x = 20;
String ch = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
graphics.setColor(getRandomColor());
int degree = random.nextInt() % 25;
int dot = random.nextInt(baseNumLetter.length());
ch = baseNumLetter.charAt(dot) + "";
sBuffer.append(ch);
graphics.rotate(degree * Math.PI / 180, x, 45);
graphics.drawString(ch, x, 45);
graphics.rotate(-degree * Math.PI / 180, x, 45);
x += 40;
}
for (int i = 0; i < 6; i++) {
graphics.setColor(getRandomColor());
graphics.drawLine(random.nextInt(width), random.nextInt(height),
random.nextInt(width), random.nextInt(height));
}
for (int i = 0; i < 30; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.setColor(getRandomColor());
graphics.fillRect(x1, y1, 2, 2);
}
return sBuffer.toString();
}
private static Color getRandomColor() {
Color[] arr={new Color(255,255,255),new Color(184,250,255),new Color(107,184,255),new Color(57,208,255),new Color(124,169,255)};
Random ran = new Random();
int index = ran.nextInt(arr.length);
return arr[index];
}
}