Servlet-Response实现验证码

package com.levizhao.response;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 200;
        int height = 100;
        // 创建对象 在内存中设置图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        // 美化图片
        //  设置背景色
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.lightGray);
        graphics.fillRect(0,0,width,height);

        // 画边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0,width-1,height-1);

        // 设置验证码字符集
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 设置字符样式
        graphics.setColor(Color.red);
        graphics.setFont(new Font("Arial",Font.ITALIC,25));
        // 生成角标
        Random ran = new Random();
        for (int i = 1; i<=4 ; i++) {
            // 获取字符的坐标
            int index = ran.nextInt(str.length());
            // 获取字符
            char ch = str.charAt(index);
            // 写验证码
            graphics.drawString(ch+" ",width/5*i,height/2);
        }


        // 生成干扰线
        graphics.setColor(Color.GREEN);
        for (int i = 0; i <15 ; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            graphics.drawLine(x1,x2,y1,y2);
        }


        // 将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
}

posted @ 2021-03-29 17:25  withLevi  阅读(44)  评论(0编辑  收藏  举报