YanZhengMaServlet
public class YanZhengMaServlet extends HttpServlet {
// 生成随机数 4位
public String makeRan(){
String randnum = new Random().nextInt(9999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4 - randnum.length(); i++) {
sb.append("0");
}
randnum = sb.toString() + randnum;
return randnum;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 生成图片
BufferedImage bufferedImage = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
// 生成一个笔
Graphics2D graphics2D = (Graphics2D)bufferedImage.getGraphics();
/*
设置背景颜色
*/
// 设置画笔颜色
graphics2D.setColor(Color.white);
// 填充颜色
graphics2D.fillRect(0 ,0, 80, 30);
// 将随机数写入图片
graphics2D.setColor(Color.BLUE);
graphics2D.setFont(new Font(null, Font.BOLD, 30));
graphics2D.drawString(makeRan(), 5, 25);
// 告诉浏览器文件类型
resp.setContentType("image/jpeg");
// 网站存在缓存, 设置为无缓存
resp.setDateHeader("expires", -1);
resp.setHeader("cache-Control" , "no-cache");
// 把图片写出去 写给浏览器
ImageIO.write(bufferedImage, "jpeg", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}