验证码案例

验证码案例

package Response;

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

@WebServlet(name = "Servlet1", value = "/Servlet1")
public class Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建对象,在内存中图片
        int weith=100;
        int height=50;
        BufferedImage  image=new BufferedImage(weith,height,BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        //2.1填充背景色
        Graphics graphics = image.getGraphics();//画笔对象
        graphics.setColor(Color.PINK);
        //2.2画边框
        graphics.fillRect(0,0,weith,height);
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0,weith-1,height-1);
        String str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";

       //生成随机角标
        Random ran=new Random();
        for(int i=1;i<=4;i++){
            int index=ran.nextInt(str.length());
            //获取字符
            char ch=str.charAt(index);//随机字符
            //2.3写验证码
            graphics.drawString(ch+"",weith/5*i,height/2);

        }
        //2.4画干扰线
        graphics.setColor(Color.green);
        //随机生成坐标点
        int x1=ran.nextInt(weith);
        int x2= ran.nextInt(weith);
        int y1=ran.nextInt(height);
        int y2= ran.nextInt(height);
        graphics.drawLine(x1,x2,y1,y2);

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

    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*分析:
        点击超链接或者图片,需要换一张
        1.给超链接和图片绑定单击事件
        2.重新设置图片的src属性值

         */
        window.onload=function (){
            //1.获取图片对象
            var img=document.getElementById("checkCode");
            //2.绑定单击事件
            img.onclick=function (){
                //加时间戳
                var date=new Date().getTime();
                img.src="Response_war_exploded/Servlet?"+date;
            }
        }


    </script>
</head>
<body>
<img id="checkCode" src="/Response_war_explodedServlet1";/>
<a id="cahnge" href="/Response_war_exploded/Servlet">看不清换一张</a>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值