输出验证码到页面

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

    /**
     * 动态生成验证码,输出到页面
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        int width=100;
        int height=50;
        //创建图片对象
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


        //美化

        //填充背景色
        Graphics graphics=image.getGraphics();//画笔对象
        graphics.setColor(Color.PINK);//设置画笔颜色
        graphics.fillRect(0,0,width,height);//填充矩形
        //画边框
        graphics.drawRect(0,0,width-1,height-1);
        //写验证码
        graphics.setColor(Color.CYAN);//设置画笔颜色
        String str="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        for (int i = 1; i <= 4; i++) {
            Random random=new Random();
            graphics.drawString(str.charAt(random.nextInt(str.length()))+"",width/5*i,height/2);
        }
        //随机画干扰线
        graphics.setColor(Color.BLUE);//设置画笔颜色
        for (int i = 0; i < 5; i++) {
            Random w=new Random();
            Random h=new Random();
            graphics.drawLine(w.nextInt(width),h.nextInt(height),w.nextInt(width),h.nextInt(height));
        }


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值