Java Web Learning note 2: generate picture verification code

Keywords: Java codec Tomcat

First, create a Java Web project named identity, and create a new Servlet named IdentityServlet below it. If the project and Servlet will not be created, please refer to my notes in the previous section: https://blog.csdn.net/h2503652646/article/details/82555695

Here is the source code of IdentityServlet.java

package com.test.identity;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class IdentityServlet extends HttpServlet {
	
	
	public static final char[] CHARS={'2','3','4','5','6','7','8','9',
			'A','B','C','D','E','F','G','H','I','J','K',
			'L','M','N','U','V','W','X','Y','P','Q','R',
			'S','T','Z'};         //These are the verification code content generated randomly on the picture
	
	
	public static Random random=new Random();
	
	
	
	//Method of obtaining 6-bit random character verification code
	public static String getRandomString(){
		StringBuffer buffer=new StringBuffer();
		
		for(int i=0;i<6;i++){
			buffer.append(CHARS[random.nextInt(CHARS.length)]);
		}
		return buffer.toString();
	}
	
	//Random colors
	public static Color getRandomColor(){
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	}
	
	
	//The reverse of a color, used in the foreground
	public static Color getReverseColor(Color c){
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}

	/**
		 * Constructor of the object.
		 */
	public IdentityServlet() {
		super();
	}

	/**
		 * Destruction of the servlet. <br>
		 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("image/jpeg");
		
		String randomString=getRandomString();   //Random string
		request.getSession(true).setAttribute("randomString", randomString);
		
		int width=100;
		int height=30;
		
		Color color=getRandomColor();
		Color reverse=getReverseColor(color);       //Reverse, for foreground
		
		BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		Graphics2D g=bi.createGraphics();
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
		g.setColor(color);
		g.fillRect(0, 0, width, height);
		g.setColor(reverse);
		g.drawString(randomString, 18, 20);    //Draw random characters
		for(int i=0, n=random.nextInt(100);i<n;i++){
			                                   //Draw up to 100 noise points
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);  //Noise points are generated by randomly selecting positions on pictures
		}
		
		
		ServletOutputStream out=response.getOutputStream();
		
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);  //Convert to JPEG format
		
		
		encoder.encode(bi);  //Encode pictures
		out.flush();
	}

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
		 * Initialization of the servlet. <br>
		 *
		 * @throws ServletException if an error occurs
		 */
	public void init() throws ServletException {
		// Put your code here
	}

}

Next, we create an HTML file to reference the image verification code. The creation method is: right click on the project identity and select New - HTML (Advanced templates), set the name to identity in the pop-up box, and then Finish. The following is the code of identity.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">   
<script>
function reloadImage(){

     document.getElementById('btn').disable=true;
     document.getElementById('identity').src='servlet/IdentityServlet?ts='+new Date().getTime();

}
</script>
<img src="servlet/IdentityServlet" id="identity" onload="btn.disabled =false; "/>
<input type=button value="Change a picture." onclick="reloadImage()" id="btn">

After all the code work is completed, deploy the project on your own Tomcat (refer to the notes in the previous section for the deployment method), start tomcat, and enter:

http://localhost:8080/identity/identity.html Enter, the effect is as follows:

Click the button to refresh and replace the verification code.

Posted by tracivia on Tue, 31 Dec 2019 03:16:52 -0800