一:代码

package com.servlet;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet(name = "ValidCodeServlet",urlPatterns = "/valid")
public class ValidCodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建画板
        BufferedImage bufferedImage=new BufferedImage(150,40,BufferedImage.TYPE_INT_RGB);

        //画图之前创建画笔并设置颜色
        Graphics2D gra=bufferedImage.createGraphics();
        gra.setColor(Color.lightGray);
        gra.fillRect(0,0,150,40);

        //创建Random对象产生0-9的随机数存于list
        List<Integer> list=new ArrayList<Integer>();
        Random random=new Random();
        for (int i=0;i<4;i++){
            list.add(random.nextInt(10));
        }

        //将所需颜色存于数组中
        Color[] colors=new Color[]{Color.BLACK,Color.CYAN,Color.MAGENTA,Color.YELLOW,Color.GREEN,Color.RED};

        //设置画笔font
        gra.setFont(new Font("宋体",Font.ITALIC|Font.BOLD,30));

        //循环4次画出数字
        for (int i=0;i<list.size();i++){
            gra.setColor(colors[random.nextInt(colors.length)]);
            gra.drawString(list.get(i)+"", i*43, 30+(random.nextInt(21)-10));
        }

        //循环两次画出实线
        for (int i=0;i<2;i++){
            gra.setColor(colors[random.nextInt(colors.length)]);
            gra.drawLine(0,random.nextInt(41),150,random.nextInt(41));
        }

        //创建流对象,并使用工具类写入
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        
        //将验证码放入session中
        HttpSession session = req.getSession();
        session.setAttribute("code",""+list.get(0)+list.get(1)+list.get(2)+list.get(3));

    }
}

jsp页面只要请求该servlet即可

<img src="/valid" width="150" height="40"/><a href="">看不清</a>

二:实现效果


For sharing , For emulating , For enterprising