简单实现验证码的登录认证。
一、工具:
idea、 springboot、 thymeleaf
二、验证码的Controller类 :
@Controller
public class CaptchaController {
@GetMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置响应头信息,告诉浏览器返回的内容类型为图片
response.setContentType("image/png");
response.setCharacterEncoding("UTF-8");
// 在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
//获取画笔
Graphics g = image.getGraphics();
//设定背景色
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, width, height);
String s="0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char [] c=s.toCharArray(); //将字符串通过toCharArray()方法,转化为字符数组
StringBuffer str=new StringBuffer();
ThreadLocalRandom crandom=ThreadLocalRandom.current();//生成随机数的current()方法
for(int i=0;i<4;i++){
char code=c[crandom.nextInt(0,s.length())];//随机获取字符数组中的一个字符
str.append(code); //将字符通过append()方法增加到字符串中
}
//取随机产生的验证码(4位数字)
Random rnd = new Random();
// nextInt 得到一个0~8999的值, 写成下面的写法是为了保证最少有4位数
g.setColor(Color.black);
g.setFont(new Font("", Font.PLAIN, 20));
g.drawString(str.toString(), 10, 17);
//将验证码存入session
// 把验证码存到session里面,等一下验证的时候需要核对验证码是否正确
// 每次刷新验证码,其实session里面的验证码也会更新
// 因为后面的值把前面的值替换掉了
request.getSession().setAttribute("randStr", str.toString());
//将验证码显示到图象中
// 随机产生100个干扰点,使图象中的验证码不易被其他程序探测到
for (int i = 0; i < 100; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
g.drawOval(x, y, 1, 1);
}
ImageIO.write(image, "png", response.getOutputStream());
// 输出图象到页面
ServletOutputStream out = response.getOutputStream();
out.flush();
out.close();
}
}
三、验证码的验证:
@Controller
public class ValidateServlet extends HttpServlet {
@Autowired
private Jwt jwt;
@Autowired
private YongHuMapper yongHuMapper;
@RequestMapping("/servlet")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html;charset=utf-8");
//得到提交的验证码
String code = request.getParameter("code");
//获取session中的验证码
System.out.println(code);
HttpSession session = request.getSession();
String randStr = (String) session.getAttribute("randStr");
System.out.println(randStr);
PrintWriter out = response.getWriter();
// request请求发过来的验证码和session里面的验证码进行核验
if (code.equals(randStr)) {
request.getSession().setAttribute("login", token);
request.getRequestDispatcher("/login").forward(request, response);
}else{
out.print("登录失败!");
}
} else {
out.println("验证码错误!");
}
}
}
四、显示验证码:
<!doctype html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<title>用户登录界面</title>
<script>
function refresh() {
// 创建一个新的XHR对象
var xhr = new XMLHttpRequest();
var newurl = "/captcha";
// 初始化一个GET请求
xhr.open('GET', newurl, true);
// 设置响应类型为blob
xhr.responseType = 'blob';
// 当请求加载完成时
xhr.onload = function () {
if (this.status === 200) {
// 创建一个新的URL表示指定的File对象或Blob对象
// 将img的src设置为新的URL
imgValidate.src = URL.createObjectURL(this.response);
}
};
xhr.send();
}
</script>
</head>
<body>
<img name="imgValidate" border=0 th:src="@{/captcha}" onclick="refresh()">
</body>
</html>
文章到此结束!