用severlet写验证码
时间: 2023-06-27 16:06:54 浏览: 169
Servlet生成验证码
下面是一个简单的用Servlet生成验证码的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 100; // 图片宽度
private static final int HEIGHT = 40; // 图片高度
private static final int LENGTH = 4; // 验证码长度
private static final String CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 验证码字符集
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setHeader("Cache-Control", "no-cache");
response.setContentType("image/jpeg");
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandomColor(200, 250));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
g.setColor(getRandomColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
String s = String.valueOf(CHARS.charAt(random.nextInt(CHARS.length())));
sb.append(s);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(s, 20 * i + 10, 25);
}
request.getSession().setAttribute("captcha", sb.toString());
ImageIO.write(image, "jpeg", response.getOutputStream());
}
private Color getRandomColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
```
这个Servlet使用了Java的AWT图形库生成了一个随机的验证码图片,并将验证码存储在Session中。要使用这个Servlet,只需要在web.xml文件中添加以下配置:
```xml
<servlet>
<servlet-name>captcha</servlet-name>
<servlet-class>your.package.name.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>captcha</servlet-name>
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
```
然后,在需要生成验证码的地方,只需要向/captcha路径发送GET请求即可得到一个验证码图片。例如:
```html
<img src="/captcha" alt="验证码">
```
阅读全文