• java生成验证码


     1 import java.awt.Color;
     2 import java.awt.Font;
     3 import java.awt.Graphics2D;
     4 import java.awt.image.BufferedImage;
     5 import java.io.IOException;
     6 import java.util.ArrayList;
     7 import java.util.List;
     8 import java.util.Random;
     9 
    10 import javax.imageio.ImageIO;
    11 import javax.servlet.ServletException;
    12 import javax.servlet.ServletOutputStream;
    13 import javax.servlet.annotation.WebServlet;
    14 import javax.servlet.http.HttpServlet;
    15 import javax.servlet.http.HttpServletRequest;
    16 import javax.servlet.http.HttpServletResponse;
    17 import javax.servlet.http.HttpSession;
    18 
    19 @WebServlet("/validcode")
    20 public class ValidCodeServlet extends HttpServlet {
    21     @Override
    22     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    23         //创建一张图片
    24         //单位:像素
    25         BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
    26         
    27         //透明的玻璃
    28         //向画板上画内容之前必须先设置画笔.
    29         Graphics2D gra = image.createGraphics();
    30         
    31         gra.setColor(Color.WHITE);
    32         //从哪个坐标开始填充, 后两个参数,矩形区域
    33         gra.fillRect(0, 0, 200, 100);
    34         
    35         List<Integer> randList = new ArrayList<Integer>();
    36         Random random =new Random();
    37         for (int i = 0 ;i<4;i++) {
    38             randList.add(random.nextInt(10));
    39         }
    40         //设置字体
    41         gra.setFont(new Font("宋体",Font.ITALIC|Font.BOLD,40));
    42         Color[] colors = new Color[]{Color.RED,Color.YELLOW,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY};
    43         for (int i = 0; i < randList.size(); i++) {
    44             gra.setColor(colors[random.nextInt(colors.length)]);
    45             gra.drawString(randList.get(i)+"", i*40, 70+(random.nextInt(21)-10));
    46         }
    47         
    48         for (int i = 0; i < 2; i++) {
    49             gra.setColor(colors[random.nextInt(colors.length)]);
    50             //画横线
    51             gra.drawLine(0, random.nextInt(101), 200, random.nextInt(101));
    52         }
    53         
    54         ServletOutputStream outputStream = resp.getOutputStream();
    55         //工具类
    56         ImageIO.write(image, "jpg", outputStream);
    57         
    58         //把验证码放入到session中
    59         HttpSession session = req.getSession();
    60         session.setAttribute("code", ""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3));
    61     }
    62 }
  • 相关阅读:
    只允许在input框输入文字,不能输入数字和其他字符
    阻止用户在input框输入数字
    centos 7.2安装和配置MongoDB
    Python基础
    Python小练习008
    Python小练习007
    Python小练习006
    Python错误集锦
    Python和MongoDB
    MongoDB笔记
  • 原文地址:https://www.cnblogs.com/WNof11020520/p/10353051.html
Copyright © 2020-2023  润新知