ssm 登录验证码
时间: 2023-07-25 18:11:41 浏览: 73
SSM(Spring+SpringMVC+MyBatis)登录验证码的实现步骤如下:
1. 在登录页面上添加一个验证码输入框和一个验证码图片;
2. 随机生成一个验证码,并将其存储到 session 中;
3. 将验证码图片输出到页面上,并将验证码图片的 URL 存储到 session 中;
4. 用户输入验证码后,将其与 session 中的验证码进行比对;
5. 如果比对成功,则继续进行登录操作;否则,提示用户验证码错误。
下面是一个简单的示例代码:
验证码生成器:
```java
public class VerifyCodeUtils {
private static final String VERIFY_CODES = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static String generateVerifyCode(int verifySize) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < verifySize; i++) {
sb.append(VERIFY_CODES.charAt(random.nextInt(VERIFY_CODES.length())));
}
return sb.toString();
}
public static BufferedImage generateImage(String verifyCode) {
int width = 100;
int height = 40;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
for (int i = 0; i < verifyCode.length(); i++) {
g.drawString(String.valueOf(verifyCode.charAt(i)), 20 * i + 10, 25);
}
g.dispose();
return image;
}
}
```
登录页面:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post">
<label>用户名:</label>
<input type="text" name="username"><br>
<label>密码:</label>
<input type="password" name="password"><br>
<label>验证码:</label>
<input type="text" name="verifyCode">
<img src="${pageContext.request.contextPath}/verifyCode" onclick="this.src='${pageContext.request.contextPath}/verifyCode?time='+new Date().getTime()"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
登录控制器:
```java
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(String username, String password, String verifyCode, HttpSession session) {
String realVerifyCode = (String) session.getAttribute("verifyCode");
if (!realVerifyCode.equalsIgnoreCase(verifyCode)) {
return "redirect:/login";
}
// 进行登录操作
return "redirect:/index";
}
@RequestMapping("/verifyCode")
public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
// 生成验证码
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
session.setAttribute("verifyCode", verifyCode);
// 输出验证码图片
BufferedImage image = VerifyCodeUtils.generateImage(verifyCode);
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
os.flush();
os.close();
}
}
```