Servlet 验证码

Servlet 验证码 代码编写

package cn.com.zheng.Servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageFilter;
import java.io.IOException;
import java.util.Random;

@WebServlet("/comple")
public class Comple extends HttpServlet {

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

        // 创建图片对象
        int with = 100;
        int height = 50;
        BufferedImage image = new BufferedImage(with, height, BufferedImage.TYPE_3BYTE_BGR);
        //美化图片
        //获取画笔工具
        Graphics graphics = image.getGraphics();

        //获取填充工具,进行填充背景se
        //设置画笔颜色
        graphics.setColor(Color.pink);
        graphics.fillRect(0, 0, with, height);
        //画边框
        graphics.setColor(Color.blue);
        graphics.drawRect(0,0,with-1,height-1);
        String s="abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
       //获取随机数对象
        Random random=new Random();
        //生成验证ma
        graphics.setColor(Color.black);
        for (int X= 1;  X<=4; X++) {
            int i = random.nextInt(s.length());
            char c = s.charAt(i);
            graphics.drawString(c+"",with/5*X,height/2);
        }
        //设置干扰线
        graphics.setColor(Color.orange);
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(with);
            int x2 = random.nextInt(with);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }

        //输出图片
        ImageIO.write(image, "png", resp.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值