使用servlet实现验证码

javaweb中使用servlet实现验证码



package com.test;

import javax.imageio.ImageIO;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/che")
public class che extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int w =120;
        int h =60;
        BufferedImage  img = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = img.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0,0,w,h);
        g.setColor(Color.blue);
        g.drawRect(0,0,w-1,h-1);
        String str ="abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRZTUVWXYZ";
        Random r = new Random();
        StringBuffer s = new StringBuffer();
        for(int i=0 ;i<4;i++) {
            int n = r.nextInt(str.length());
            String ss = str.substring(n,n+1);
            s.append(ss);
            g.drawString(ss,20*(i+1),15);
        }

        g.setColor(Color.GREEN);
        g.drawLine(5,25,100,30);
        g.setColor(Color.RED);
        g.drawLine(2,7,110,45);
        g.setColor(Color.YELLOW);
        g.drawLine(0,58,115,0);
        g.setColor(Color.BLACK);
        g.drawLine(50,0,50,60);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(img,"jpg",out);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request ,response);
    }
}

``




## //html代码

1,输出验证码
2,点击刷新
<html>
<head>
<script>
    window.onload = function() {
        var che = document.getElementById('v');
        che.onclick = function () {
            var d = new Date();
            this.src = "/aaa/che?time="+d.getTime();
        }
    }

</script>
    <title>Title</title>
</head>
<body>
<form>
    
    <img src="/aaa/che" id="v">
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不俏子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值