生成简单的验证码
简单的验证码
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: 可根据注释改变颜色和背景色
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!