1. 前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码</title>
</head>
<script type="text/javascript">
function changeCode() {
document.getElementById("img").src = "/imgCode?r=" + new
Date().getTime();
}
</script>
<body>
<form action="/day04/login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="code"></td>
</tr>
<tr>
<td></td>
<td><img id="img" src="/imgCode" onclick="changeCode();"/><a
href="javascript:;" onclick="changeCode();">换一换</a></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登陆"></td>
</tr>
</table>
</form>
</body>
</html>
2.后端代码
package com.imgcode.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @version 1.0
* @author:
* @date:
*/
@RestController
public class ImgController {
@RequestMapping("/imgCode")
public void imgCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
// 创建画布
int width = 180;
int height = 60;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获得画笔
Graphics g = bufferedImage.getGraphics();
// 填充背景颜色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 绘制边框
g.setColor(Color.WHITE);
g.drawRect(0, 0, width-1, height-1);
// 生成随机字符
// 准备数据
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
// 准备随机对象
Random r = new Random();
// 声明一个变量 保存验证码
String code = "";
// 书写4个随机字符
for (
int i = 0;
i < 4; i++) {
// 设置字体
g.setFont(new Font("宋体", Font.BOLD, 28));
// 设置随机颜色
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
String str = data.charAt(r.nextInt(data.length())) + "";
g.drawString(str, 10 + i * 28, 30);
// 将新的字符 保存到验证码中
code = code + str;
}
// 绘制干扰线
for (
int i = 0;
i < 6; i++) {
// 设置随机颜色
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width),
r.nextInt(height));
}
// 将验证码 打印到控制台
System.out.println(code);
// 将验证码放到session中
request.getSession().setAttribute("code_session", code);
// 将画布显示在浏览器中
// 将画布显示在浏览器中
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
}
将以上代码直接复制粘贴就可以生成验证码了,验证码的样式在后端代码中控制,请看后端代码注释。