生成验证码

doPost

    private final int WIDTH = 150;
    private final int HEIGHT = 30;
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        BufferedImage bf = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = (Graphics2D) bf.getGraphics();//Graphics's son is powerful
        graphics.setColor(Color.BLUE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        graphics.setColor(Color.red);
        graphics.setFont(new Font("楷体",Font.BOLD,20));
        Random random = new Random();
        int m = 13;
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(base.length());
            char charAt = base.charAt(index);

            int jiaodu = random.nextInt(60)-30;
            double theta = jiaodu*Math.PI/180;//弧度
            graphics.rotate(theta, m, 19);

            graphics.drawString(charAt+"", m, 15);

            graphics.rotate(-theta, m, 19);
            m+=20;
        }
        for (int i = 0; i < 4; i++) {
            graphics.setColor(Color.white);
            graphics.drawLine(random.nextInt(WIDTH),random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(HEIGHT));
        }
        ImageIO.write(bf, "png",response.getOutputStream());
    }

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function changeImage() {
        document.getElementById("myimage").src="response/pic?" + new Date().getTime();
    }
</script>
</head>
<body>
    <form action="response/response_other" method="post">
        <input type="text" name="username"><br/>
        <input type="password" name="password"><br/>
        <input type="text" name="checkcode"><br/>
        <img src="response/pic" style="cursor: pointer;" onclick="changeImage();" id="myimage"><br>
        <input type="submit" value="登录">        
    </form>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值