zoukankan      html  css  js  c++  java
  • 验证码设计

    package cn.it.web.controller;


    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;


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


    public class ImageServlet extends HttpServlet {
     int width = 80;
     int height = 20;
     char[] buf = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ".toCharArray();


     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {
      BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);
      Graphics g = image.getGraphics();
      // 填充背景
      g.setColor(Color.WHITE);
      g.fillRect(0, 0, width, height);
      // 画框
      g.setColor(Color.BLACK);
      g.drawRect(0, 0, width - 1, height - 1);
      // 写字符
      g.setColor(Color.BLUE);
      g.setFont(new Font("粗体", Font.BOLD, 15));
      Random r = new Random();
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < 4; i++) {
       int pos = r.nextInt(buf.length);
       char c = buf[pos];
       sb.append(c);
       g.drawString(String.valueOf(c), (i * 2 + 1) * (width / 9), 15);
      }
      String code = sb.toString();
      // 将验证码存入session
      req.getSession().setAttribute("code", code);
      ImageIO.write(image, "jpeg", resp.getOutputStream());
     }


     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {
      doGet(req, resp);
     }
    }

  • 相关阅读:
    Bit Manipulation
    218. The Skyline Problem
    Template : Two Pointers & Hash -> String process
    239. Sliding Window Maximum
    159. Longest Substring with At Most Two Distinct Characters
    3. Longest Substring Without Repeating Characters
    137. Single Number II
    142. Linked List Cycle II
    41. First Missing Positive
    260. Single Number III
  • 原文地址:https://www.cnblogs.com/qq809306794/p/3176600.html
Copyright © 2011-2022 走看看