zoukankan      html  css  js  c++  java
  • JavaWeb10-Servlet实现随机产生图片验证码

    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);
    }
    }
  • 相关阅读:
    入门经典 第七章 7.3.3 二进制生成子集
    gdb调试方法简要总结
    Erlang_1
    hdu 1144
    创建一个类,重载运算符实现多项式的加,减,乘运算
    ubuntu12.04 iNodeClient 连校园网
    ftime使用
    CodeForce 264 A. Escape from Stones
    hdu 1161 Eddy's mistakes
    hdu 1064
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583666.html
Copyright © 2011-2022 走看看