Servlet way to realize verification code--Javaweb

content

Hands-on practice: Servlet way experimental verification code

1. Constant string as verification code

This is a servlet that generates a constant string verification code 

The captcha page shows yanzehngma.jsp

Verification code display:

2. Use a defined character library to implement dynamic verification code

Code:

The implementation is as follows (Ctrl+F5 to refresh the page)

 draw some distracting lines

 Optimized code (all code)

Servlet:

 JSP:

Effect picture:

Please see the next article for the upgraded version:

(1 message) Servlet way to realize verification code--Javaweb (upgrade / full version) - Xiao Sun's code sharing blog - CSDN Blog


 

Hands-on practice: Servlet way experimental verification code

First, we test the program with a constant string as a verification code, and then turn the constant string into a variable to generate a dynamic verification code.

1. Constant string as verification code

This is a servlet that generates a constant string verification code 

package random.code;
import sun.net.www.content.text.Generic;
<%--
  Created by IntelliJ IDEA.
  User: 86130
  Date: 2022/4/24
  Time: 17:05
  To change this template use File | Settings | File Templates.
--%>
<%@ pa

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.IOException;

@WebServlet("/yanzhengma")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //get 请求和 post 请求一样,直接交给post处理,回调doPost
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post 请求中写业务功能
        //几板斧 哈哈
        resp.setContentType("text/html;charset=utf-8");
        int width=120;
        int height=30;
        //创建一个内存中带缓存的图片对象
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //获取2D画笔对象
        Graphics g=image.getGraphics();
        //给画笔对象设置颜色,为图片喷绘背景色
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);
        //设置颜色,绘制图片边框
        g.setColor(Color.black);
        g.drawRect(1,1,width-2,height-2);


        //先使用一个常量字符串测试程序设计思路 String
        String str1="J L O K";
        g.setColor(Color.RED);
        g.setFont(new Font("宋体",Font.ITALIC,20));
        g.drawString(str1,15,22);



        //使用响应对象的字节输出流,写到客户端浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }
}

The captcha page shows yanzehngma.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86130
  Date: 2022/4/24
  Time: 17:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<center>
<h2>登录验证码</h2>
验证码:<input type="text" name="random">&nbsp;<img src="yanzhengma"><br>
<input type="submit" value="登录"><br>
</center>
</body>
</html>

Verification code display:

 

 This proves that the design idea is correct, and then we will implement the dynamic verification code.

2. Use a defined character library to implement dynamic verification code

Code:

Build a character warehouse, and randomly combine the verification code according to the random read string subscript.

public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //get 请求和 post 请求一样,直接交给post处理,回调doPost
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post 请求中写业务功能
        //几板斧 哈哈
        resp.setContentType("text/html;charset=utf-8");
        int width=120;
        int height=30;
        //创建一个内存中带缓存的图片对象
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //获取2D画笔对象
        Graphics g=image.getGraphics();
        //给画笔对象设置颜色,为图片喷绘背景色
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);
        //设置颜色,绘制图片边框
        g.setColor(Color.black);
        g.drawRect(1,1,width-2,height-2);


        //先使用一个常量字符串测试程序设计思路 String
        String yzm="";
        //想办法将yzm,在0-9和a-z、A-Z中随机组合4个字符的字符串  定义一个字符仓库
        String baseChar="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        //随机数对象
        Random rd=new Random();
        for (int i = 0; i <4; i++) {
            int pos=rd.nextInt(baseChar.length());
            yzm=yzm+" "+baseChar.charAt(pos);

        }
        g.setColor(Color.RED);
        g.setFont(new Font("宋体",Font.ITALIC,20));
        g.drawString(yzm,15,22);
        
        //使用响应对象的字节输出流,写到客户端浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}

The implementation is as follows (Ctrl+F5 to refresh the page)

 draw some distracting lines

/*
         * 在图片上画随机线条
         * @param g
         * */
        g.setColor(Color.blue);
        for (int i = 0; i < 10; i++) {
            int x1= rd.nextInt(width);
            int y1=rd.nextInt(height);
            int x2= rd.nextInt(width);
            int y2= rd.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }

accomplish:

 Optimized code (all code)

Servlet:

package random.code;
import sun.net.www.content.text.Generic;

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.IOException;
import java.util.Random;

@WebServlet("/yanzhengma")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //get 请求和 post 请求一样,直接交给post处理,回调doPost
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post 请求中写业务功能
        //几板斧 哈哈
        resp.setContentType("text/html;charset=utf-8");
        int width=120;
        int height=30;
        //创建一个内存中带缓存的图片对象
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //获取2D画笔对象
        Graphics g=image.getGraphics();
        //给画笔对象设置颜色,为图片喷绘背景色
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);
        //设置颜色,绘制图片边框
        g.setColor(Color.black);
        g.drawRect(1,1,width-2,height-2);


        //先使用一个常量字符串测试程序设计思路 String
        String yzm="";
        //想办法将yzm,在0-9和a-z、A-Z中随机组合4个字符的字符串  定义一个字符仓库
        String baseChar="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        //随机数对象
        Random rd=new Random();
        for (int i = 0; i <4; i++) {
            int pos=rd.nextInt(baseChar.length());
            yzm=yzm+" "+baseChar.charAt(pos);

        }
        g.setColor(Color.RED);
        g.setFont(new Font("宋体",Font.ITALIC,20));
        g.drawString(yzm,15,22);
        //绘制一些干扰线
        /*
         * 在图片上画随机线条
         * @param g
         * */
        g.setColor(Color.blue);
        for (int i = 0; i < 10; i++) {
            int x1= rd.nextInt(width);
            int y1=rd.nextInt(height);
            int x2= rd.nextInt(width);
            int y2= rd.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }

        //给客户端设置MINE类型
        resp.setHeader("content-type","image/jpeg");
        //使用响应对象的字节输出流,写到客户端浏览器
        //设置响应头控制浏览器不要缓存
        resp.setDateHeader("expries", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");

        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}

 JSP:

<%--
  Created by IntelliJ IDEA.
  User: 86130
  Date: 2022/4/24
  Time: 17:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        window.onload=function changeImg() {
            var img=document.getElementById("randomImg");
            //给img对象绑定一个点击事件
            img.onclick=function () {
                //鼠标每单击一次验证码图片,设置img标签的src属性,然后图片标签就会调用src指向的资源
                var time=new Date().getTime();
                img.src="yanzhengma?id="+time;

            }
        }

    </script>
</head>
<body>
<center>
<h2>登录验证码</h2>
    账号:<input type="text" name="random"><br>
    密码:<input type="text" name="random"><br>
验证码:<input type="text" name="random">&nbsp;<img id="randomImg" src="yanzhengma"><a href="#" onclick="changeImg()">看不清,换一张</a><br>
<input type="submit" value="登录"><br>
</center>
</body>
</html>

Effect picture:

Please see the next article for the upgraded version:

(1 message) Servlet way to realize verification code--Javaweb (upgrade / full version) - Xiao Sun's code sharing blog - CSDN Blog

Guess you like

Origin blog.csdn.net/weixin_53939785/article/details/124387396