@[TOC]

Use servlets to generate captcha

How do I use servlets to generate captcha

In Java, we can use Servlet to generate verification code in Web projects. The process is as follows: the front-end requests the corresponding address of the verification code Servlet, the back-end Servlet receives the request, generates a string of characters as the verification code, stores it into the Session, and finally returns the verification code as a picture to the front-end. A verification code is filled in at the front end and submitted to the server for verification.

Let’s look at an example from which you can also implement captchas step by step in the right editor.

With the project and servlet created, we first register the servlet in the web.xml file.

steps

Write code to generate image captcha in the servlet’s doGet() method:

It is divided into the following steps:

  1. Define image data buffer;

  2. Create a picture object;

  3. Create a drawing tool (Graphics);

  4. Generate random numbers and store them in session;

  5. Use Graphics to draw Graphics;

  6. Output the verification code to the client through the image output stream (ImageIO);

  7. Finally enter the address of the verification code to access the single verification code.

The code is as follows:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Steps to use the captcha
    // Define the width and height of the image
    int height = 20;
    int width = 60;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // Drawing tool
    Graphics graphics = image.getGraphics();
    // Draw a rectangle
    graphics.setColor(getRandColor());
    // The first two parameters to draw the rectangular background are the coordinates of x and y
    graphics.fillRect(0.0, width, height);
    // Set the text color to white
    graphics.setColor(Color.WHITE);
    String yzm = "";
    // Generate four random numbers and draw them on the picture
    for (int i = 1; i <= 4; i++) {
        // Generate random numbers and display them on the page
        int number = new Random().nextInt(10);
        yzm += number;
        graphics.drawString(number + "".10 * i, 10);
    }
    // Put the verification code into Httpsession
    HttpSession session = req.getSession();
    session.setAttribute("sessionYzm", yzm);
    // Print the captcha image to the client
    ImageIO.write(image, "jpg", resp.getOutputStream());
}
// Get a random color
private Color getRandColor(a) {
    int red = new Random().nextInt(255);
    int green = new Random().nextInt(255);
    int blue = new Random().nextInt(255);
    return new Color(red, green, blue);
}
Copy the code

The effect is as follows:

Captcha cases:

Case 1:

The effect

html

In HTML, clicking on the IMG tag (captcha image) will request a servlet response to redraw the captcha pattern.

<div class="verify">
	<input name="check" type="text" placeholder="Please enter the verification code." autocomplete="off">
	<span><img src="checkCode" alt="" onclick="changeCheckCode(this)"></span>
	<script type="text/javascript">
		// Image click event
		function changeCheckCode(img) {
			img.src="checkCode?"+new Date().getTime();
			// console.log	(new Date().getTime());
			/ / timestamp
		}

	</script>
</div>
Copy the code

servlet

package cn.itcast.travel.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.IOException;
import java.util.Random;

/** * Verification code */
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		// The server tells the browser not to cache
		response.setHeader("pragma"."no-cache");
		response.setHeader("cache-control"."no-cache");
		response.setHeader("expires"."0");
		
		// Create an image in memory that is 80 by 30 with a black background by default
		// Parameter one: long
		// Parameter two: width
		// Parameter 3: color
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		// Get the brush
		Graphics g = image.getGraphics();
		// Set the brush color to grey
		g.setColor(Color.GRAY);
		// Fill the image
		g.fillRect(0.0, width,height);
		
		// Generate 4 random captcha, 12Ey
		String checkCode = getCheckCode();
		// Put the verification code into HttpSession
		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
		
		// Set the brush color to yellow
		g.setColor(Color.YELLOW);
		// Set the font size
		g.setFont(new Font("Black",Font.BOLD,24));
		// Write a captcha to the image
		g.drawString(checkCode,15.25);
		
		// Outputs the image in memory to the browser
		// Parameter one: image object
		// Parameter 2: Image format, such as PNG,JPG,GIF
		// Where does the image output go
		ImageIO.write(image,"PNG",response.getOutputStream());
	}
	/** * produces a random 4-bit string */
	private String getCheckCode(a) {
		String base = "0123456789ABCDEFGabcdefg";
		int size = base.length();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=1; i<=4; i++){// Generate random values from 0 to size-1
			int index = r.nextInt(size);
			// Get the index character in the base string
			char c = base.charAt(index);
			// Put c into a StringBuffer
			sb.append(c);
		}
		return sb.toString();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response); }}Copy the code

Case 2:

The effect

servlet

public class ResponseDemo3 extends HttpServlet {

    /** * output image *@param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int width = 200;
        int height = 35;
        /** * create the image memory object * 2. Get the brush * 3. Set the color, draw the rectangle border * 4. Set the color, fill the rectangle * 5. Set the color, draw the interference line * 6. Set the color, draw the captcha * 7. Export the memory image to the browser */
        // Create memory image
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);// Parameters: width, height (all pixels), format (RGB)
        Graphics g = image.getGraphics();// Only one brush

        // Set the color
        g.setColor(Color.BLUE);
        / / picture frame
        g.drawRect(0.0, width, height);

        // Set the color
        g.setColor(Color.GRAY);
        // Fill the rectangle
        g.fillRect(1.1, width-2, height-2);

        // Set the color
        g.setColor(Color.WHITE);
        // Get a random number object
        Random r = new Random();
        // Draw 10 interference lines
        for(int i=0; i<10; i++){ g.drawLine(r.nextInt(width), r.nextInt(height),r.nextInt(width), r.nextInt(height)); }// Set the color
        g.setColor(Color.RED);
        // Change font size
        Font font = new Font("宋体", Font.BOLD,30);// Argument: 1 font name. Font style 3. Font size
        g.setFont(font);// Set the font
        // Draw four verification codes
        int x = 35;// The first x-coordinate is 35 pixels
        for(int i=0; i<4; i++){//r.next (10)+"
            g.drawString(String.valueOf(r.nextInt(10)), x, 25);
            x+=35;
        }

        // Output to the browser
        // Parameters: 1. Memory object. 2. Output image format. 3. The output stream used
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { doGet(request, response); }}Copy the code