验证码简单例子

  • 本质:图片
  • 目的:防止恶意表单注册

先输出一张简单的图片

 资源ServletDemo5代码

package com.lingaolu.servlet;

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

/**
 * @author 林高禄
 * @create 2020-07-12-17:52
 */
@WebServlet("/servletDemo5")
public class ServletDemo5 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        // 创建内存中的图片
        BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}

浏览器访问

验证码简单例子_第1张图片

往图片加验证码

package com.lingaolu.servlet;

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

/**
 * @author 林高禄
 * @create 2020-07-12-17:52
 */
@WebServlet("/servletDemo5")
public class ServletDemo5 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        // 创建内存中的图片
        BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
        // 美化图片,填写验证码
        Graphics g = image.getGraphics();
        // 填充黄色
        g.setColor(Color.YELLOW);
        g.fillRect(0,0,width,height);
        // 边框蓝色
        g.setColor(Color.blue);
        g.drawRect(0,0,width-2,height-2);
        // 填写验证码
        String str = "あいうえおかきくけこさしすせそたちつてとなにぬんへのはひふへほまみむめもやゆよらりるれろわを";
        int length = str.length();
        Random ran = new Random();
        for(int i=1;i<=4;i++){
            g.drawString(str.charAt(ran.nextInt(length))+"",i*width/5,height/2);
        }
        // 画干扰线
        g.setColor(Color.GREEN);
        for(int i=0;i<10;i++){
            g.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
        }
        // 将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}

浏览器访问

验证码简单例子_第2张图片

加一个页面d.html,可以刷新验证码




    
    验证码


   
   看不清换一张?
   

启动,访问d.html

验证码简单例子_第3张图片

单击厌验证码或者文字,都可以刷新验证码了。

你可能感兴趣的:(Web核心,验证码,表单)