Java验证码工具类 :
public class PhoneCode {
private BufferedImage codeImg;
private String codeStr;
private static char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
public final String SESSION_CODE_NAME="code";
private PhoneCode(){
init();
}
public static PhoneCode codeInstance(){
return new PhoneCode();
}
public BufferedImage getCodeImg(){
return this.codeImg;
}
public String getCodeStr(){
return codeStr;
}
private Color getRandColor(int x,int y){
Random random = new Random();
if (x>255){
x=255;
}
if (y>255){
y=255;
}
int r = x+random.nextInt(y-x);
int g = x+random.nextInt(y-x);
int b = x+random.nextInt(y-x);
return new Color(r,g,b);
}
private void init(){
int width = 85;
int height = 20;
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
Random random = new Random();
graphics.setColor(getRandColor(200,250));
graphics.fillRect(0,0,width,height);
graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
graphics.setColor(getRandColor(160,200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
graphics.drawLine(x,y,x+x1,y+y1);
}
String phoneCode = "";
for (int i = 0; i < 6; i++) {
String onCode = String.valueOf(code[random.nextInt(code.length-1)]);
phoneCode+=onCode;
graphics.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
graphics.drawString(onCode,13*i+6,16);
}
codeStr=phoneCode;
graphics.dispose();
codeImg = bufferedImage;
}
}
controller:
@Controller
public class PhoneCodeController {
@RequestMapping(value = "/getCode")
@ResponseBody
public void getPhoneCode(HttpServletResponse response,HttpServletRequest request){
response.setHeader("Expires","-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "-1");
PhoneCode phoneCode = PhoneCode.codeInstance();
//连接redis,将验证码放入redis中
long seconds = 60;
String codeStr = phoneCode.getCodeStr();
JedisCommon jedisCommon = new JedisCommon();
Jedis jedis = jedisCommon.jedisUtil();
jedis.setex(request.getParameter("phoneNum"),seconds,codeStr);
jedis.close();
try {
//最主要的就是这个
ImageIO.write(phoneCode.getCodeImg(),"jpg",response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
html:
<script type="text/javascript" src="webjars/jquery/3.6.0/jquery.js"></script>
<script>
function reloadCode() {
var dateJson = new Date().getTime();
let object = document.getElementById("phoneNum").value;
document.getElementById("imgSignCode").src="/getCode?r="+dateJson+"&phoneNum="+object;
}
</script>
<body>
手机号:<input id="phoneNum" type="text" name="phoneNum"><br/>
<img id="imgSignCode" src="" onclick="reloadCode()" title="重新获取" style="cursor:pointer;"/>
</body>
其中src是到对应controller获取验证码的请求地址。
验证的话就是直接从redis中获取key对应的值。
key是手机号。