Web-验证码生产

hwly

package cn.itcast.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Random;
import java.util.Set;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            int width=100;
            int height=50;
            BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//创建一个图片对象,在内存中显示

            Graphics g=image.getGraphics();//画笔对象
            g.setColor(Color.PINK);//设置画笔颜色为粉红
            g.fillRect(0,0,width,height);

            g.setColor(Color.BLUE); //边框
            g.drawRect(0,0,width,height);

            //写验证码
            Random ran = new Random();
            for (int i=1;i<=4;i++) {
    
    
                //生产随机下标
                String str = "ABCDEFGHIJKLMNOQPRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                int index = ran.nextInt(str.length());
                char ch = str.charAt(index);
                g.drawString(ch+"", width/5*i, height/2);
            }
            //画干扰线
            g.setColor(Color.GREEN);

            //随机生产坐标
            for(int i=0;i<10;i++) {
    
    
                int x1 = ran.nextInt(width);
                int x2 = ran.nextInt(width);

                int y1 = ran.nextInt(height);
                int y2 = ran.nextInt(height);
                g.drawLine(x1,y1,x2,y2);
            }
            ImageIO.write(image,"jpg",response.getOutputStream());//将页面输出展示
    }

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

利用js完成单击图片实现验证码切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //获取图片对象
        var img=document.getElementById("checkCode");
        //绑定单击事件
        img.onclick=function () {
    
    
            var date=new Date().getTime();
            //利用时间戳使参数永不重复
            img.src="/tomcatt/checkCodeServlet?"+date;///tomcatt/checkCodeServlet如果这样写点击图片不会完成切换,因为路径未改变
            //?:http get请求携带参数

        }
    </script>
</head>
<body>
        <img id="checkCode" src="/tomcatt/checkCodeServlet"/>
        <a id="change" href="">kbqhyz</a>
</body>
</html>`

猜你喜欢

转载自blog.csdn.net/qq_47154574/article/details/109754717