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);
    }
    }
  • 相关阅读:
    常见问题
    查询
    多对多关系
    prototype & __proto__
    new operator
    用户
    express.Router
    Express 应用生成器
    LeanCloud
    npm常用命令
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583666.html
Copyright © 2011-2022 走看看