生成简单的验证码
作者:互联网
简单的验证码
package org.example.servlet;
import com.sun.javafx.iio.ImageStorage;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage bufferedImage = new BufferedImage(120, 80, BufferedImage.TYPE_INT_RGB);
//获得画笔对象
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
//设置图片的背景颜色
graphics.setColor(Color.black);
graphics.fillRect(0,0,120,80);
//给图片写数据
graphics.setColor(Color.white);
graphics.setFont(new Font("",Font.BOLD,20));
for (int i = 0; i < 4; i++) {
graphics.drawString(getRandomData(),20*i+20,50);
}
//告诉浏览器,这个请求以图片的形式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
}
private String getRandomData(){
String data="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int rand=new Random().nextInt(data.length());
return String.valueOf(data.charAt(rand));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
验证码样式
ps: 可根据注释改变颜色和背景色
标签:BufferedImage,resp,graphics,验证码,生成,简单,import,servlet,javax 来源: https://www.cnblogs.com/yts-helloworld/p/15400471.html