1.创建一个新的Java项目,并设置好项目的基本配置。
2.导入依赖:
1.如果使用Maven进行项目管理,在项目的pom.xml文件中添加以下依赖:
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15.RELEASE</version>
</dependency>
</dependencies>
2.或者 手动下载相应的jar包,并将它们添加到项目的类路径中 在笔记本或电脑的“命令提示符”(CMD窗口)输入maven导入命令 导入项目 添加依赖
3.创建验证码生成器类:
package www.com.sina1.controller;
import cn.dsna.util.images.ValidateCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description:用于验证码的控制层实现类
*/
@Controller
@RequestMapping("/captcha")
public class CaptchaController {
/**
* @description:显示验证码的图片的功能方法
* @param w 验证码的宽
* @param h 验证码的高
* @param c 验证码码值数量
* @param n 防伪线数量
* @param request
* @param response
* @return: void
* @date: 2024/2/23 18:13
*/
@RequestMapping("/img/{w}/{h}/{c}/{n}")
public void getCaptchaImg(
@PathVariable int w,
@PathVariable int h,
@PathVariable int c,
@PathVariable int n,
HttpServletRequest request, HttpServletResponse response
) throws IOException {
// 1- 生成验证码对象
ValidateCode validateCode = new ValidateCode(w, h, c, n);
// 2- 通过验证码对象,生成一个验证码码值
// 放在作用域,为登录判断作准备
String code = validateCode.getCode();
request.getSession().setAttribute("code", code);
// 3- 通过数据流的方式,返回一个图片流给前端显示验证码
validateCode.write(response.getOutputStream());
}
}
4.前端显示验证码图案 方式:
<table>
<tr><td>用户名: <input type="text" name="username" id="username"></td></tr>
<tr><td>密码: <input type="text" name="password" id="password"></td></tr>
<tr><td>验证码: <input type="text" name="captcha" id="captcha">
<img src="/captcha/img/50/20/1/20" width="50" height="20"></td></tr>
<tr><td> <input type="button" value="登录" onclick="toLogin();"></td></tr>
</table>
5.输入验证码提交到后端登录验证
6.后端开始验证 因为创建验证码时将验证码的值存到了session作用域 所有可以直接获取验证
String code= (String) request.getSession().getAttribute("code");
if (code.trim().length()==0) {
return ResultUtil.error("非法登录");
}
if (!code.toLowerCase().equals(user.getCaptcha().toLowerCase())) {
return ResultUtil.error("验证码错误");
}
这样就实现了简易的验证码图案的创建及使用