• 图形验证码的实现


    package work;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;

    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class checkcode extends HttpServlet {
     public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
      request.setCharacterEncoding("UTF-8");
      response.setContentType("image/jpeg");
      HttpSession session=request.getSession();
      int width=60;
      int height=20;
      response.setHeader("Pragma","NO-cache");
      response.setHeader("Cache-Control","no-cache");
      response.setDateHeader("Expires",0);
      BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
      Graphics g=image.getGraphics();
      String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      char[] rands=new char[4];
      for(int i=0;i<4;i++){
       int rand=(int)(Math.random()*36);
       rands[i]=chars.charAt(rand);
      }
      g.setColor(new Color(0xDCDCDC));
      g.fillRect(0, 0, width, height);
      for(int i=0;i<120;i++){
       int x=(int)(Math.random()*width);
       int y=(int)(Math.random()*height);
       int red=(int)(Math.random()*255);
       int green=(int)(Math.random()*255);
       int blue=(int)(Math.random()*255);
       g.setColor(new Color(red,green,blue));
       g.drawOval(x, y, 1, 0);
      }
      g.setColor(Color.BLACK);
      g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
      g.drawString(""+rands[0], 1, 17);
      g.drawString(""+rands[1], 16, 15);
      g.drawString(""+rands[2], 31, 18);
      g.drawString(""+rands[3], 46, 16);
      g.dispose();
      ServletOutputStream sos=response.getOutputStream();
      ByteArrayOutputStream baos=new ByteArrayOutputStream();
      ImageIO.write(image, "JPEG", baos);
      byte[] buffer=baos.toByteArray();
      response.setContentLength(buffer.length);
      sos.write(buffer);
      baos.close();
      sos.close();
      session.setAttribute("checkcode", new String(rands));
     }
    }

  • 相关阅读:
    币圈惊现门罗币挖矿新家族「罗生门」
    5步告诉你QQ音乐的完美音质是怎么来的,播放器的秘密都在这里
    【云+社区极客说】新一代大数据技术:构建PB级云端数仓实践
    Android P的APP适配总结,让你快人一步
    C++11用于计算函数对象返回类型的统一方法
    C++11用于元编程的类别属性
    C++11多态函数对象包装器
    C++11包装引用
    C++11能用智能指针
    C++正则表达式
  • 原文地址:https://www.cnblogs.com/lls1350767625/p/7912566.html
Copyright © 2020-2023  润新知