spring框架写一个验证码
时间: 2024-05-01 12:22:05 浏览: 106
Spring验证码
在Spring框架中,可以使用Java Servlet API提供的类库来生成和验证验证码。下面是一个简单的示例:
1. 在web.xml文件中添加servlet和servlet-mapping配置
```xml
<servlet>
<servlet-name>captchaServlet</servlet-name>
<servlet-class>com.example.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>captchaServlet</servlet-name>
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
```
2. 创建CaptchaServlet类
```java
package com.example;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int IMG_WIDTH = 120;
private static final int IMG_HEIGHT = 40;
private static final int CODE_LENGTH = 4;
private static final String SESSION_KEY = "captcha_code";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建验证码图片
BufferedImage bi = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Random r = new Random();
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
String code = "";
for (int i = 0; i < CODE_LENGTH; i++) {
String s = String.valueOf(r.nextInt(10));
code += s;
g.drawString(s, 20 * i + 10, 25);
}
HttpSession session = request.getSession();
session.setAttribute(SESSION_KEY, code);
response.setContentType("image/png");
ImageIO.write(bi, "png", response.getOutputStream());
}
}
```
3. 在JSP页面中添加验证码输入框和图片
```html
<form method="post" action="/login">
<label for="captcha">验证码:</label>
<input type="text" name="captcha" id="captcha" />
<img src="/captcha" alt="验证码" />
<button type="submit">登录</button>
</form>
```
4. 在登录请求处理方法中验证验证码
```java
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("captcha") String captcha,
HttpSession session) {
String expected = (String) session.getAttribute("captcha_code");
if (!captcha.equals(expected)) {
return "login_failed";
}
// 验证用户名和密码
// ...
}
```
以上就是一个简单的Spring框架下生成和验证验证码的示例。
阅读全文