The origin of a verification code
In web project development, in order to prevent some people from using automatic tools (such as automatic registration machines) to process batch data, verification codes are added to verify in different functional nodes to achieve the effect of blocking the automatic software
The most classic applications are: website registration graphic verification code; next, through Java technology, combined with servlet, a graphic verification code program required for website registration is implemented, for your reference.
2. Implement the graphic verification code effect of registration page
1. Create a web project: java_servlet_verifyimg
2. Create a controller that automatically generates graph verification codes - VerifyImgServlet
package com.phome.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.IOException;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 VerifyImgServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; // Set a random character dictionary. 0,o,1,I, etc. public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static Random random = new Random(); // Random number object public static String getRandomString() { StringBuffer buffer = new StringBuffer(); // String cache for (int i = 0; i < 6; i++) // Six loops to get characters { buffer.append(CHARS[random.nextInt(CHARS.length)]); // Take one character randomly at a time} return buffer.toString(); } public static Color getRandomColor() { return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } public static Color getReverseColor(Color c) { return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue()); } public static Color getReverseColor(Color c) { return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue()); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); // Set the output type to not omit String randomString = getRandomString(); // Call the method to generate random string to get and accept the random string request.getSession(true).setAttribute("randomString", randomString); // Store the string in the Session int width = 100; // Image width int height = 30; // Image height Color color = getRandomColor(); // Get random color for background color Color reverse = getReverseColor(color); // Invert color for foreground color BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Create a color image Graphics2D g = bi.createGraphics(); // Get the drawing object g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16)); // Set font g.setColor(color); // Set color g.fillRect(0, 0, width, height); // Draw the background g.setColor(reverse); // Set the color 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); // Random noise points} ServletOutputStream out = response.getOutputStream(); // It seems to be getting the output stream JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // Encoder encoder.encode(bi); // Encoding the image out.flush(); // Output to the client} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}3. Create a Register Controller - RegistServlet
package com.phome.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Registration controller* @author ZuoYi * */public class RegistServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Get the registration random verification code from the session HttpSession session = req.getSession(); String randomString = (String)session.getAttribute("randomString"); // Get the user input verification code String inputRandomString = req.getParameter("randomStr"); // Make sure the verification code is passed, and register it simulates if (randomString.equals(inputRandomString)) { req.setAttribute("resinfo", "Congratulations! Registration was successful!"); } else { req.setAttribute("resinfo", "The verification code is entered incorrectly, please check and register again!"); } // If the registration is successful or failed, jump to the result.jsp page to view the registration results. . . req.getRequestDispatcher("result.jsp").forward(req, resp); } }4. Configure servlet
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>simg</display-name> <!-- Configure user registration servlet --> <servlet> <servlet-name>registservlet</servlet-name> <servlet-class>com.phome.servlet.RegistServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>registservlet</servlet-name> <url-pattern>/regist.action</url-pattern> </servlet-mapping> <!-- Configure graph verification code servlet --> <servlet> <servlet-name>verifyimg</servlet-name> <servlet-class>com.phome.servlet.VerifyImgServlet</servlet-class> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>verifyimg</servlet-name> <url-pattern>/verifyimg.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list></web-app>
5. Create a registration view test page - regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> <form action="${pageContext.request.contextPath}/regist.action" method="post"> Username: <input type="text" name="username"/> <br /> Password: <input type="text" name="password"/> <br /> Please enter the verification code to register: <img src="${pageContext.request.contextPath }/verifyimg.action"/> <input type="text" name="randomStr"/> <br /> <input type="submit" value="regist"/> </form> </body></html> 5.1 Create a registration result page - result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> ${requestScope.resinfo } </body></html>6. Test
(1) a. Open the browser and enter the test address: http://localhost:8080/java_servlet_verifyimg; the page shown in the figure below appears
b. Enter the registration account, password and verification code and click regist to submit
c. Test results, jump to the transfer registration page, prompting that the registration is successful
(2) Open the registration page
Enter the error registration code
Test results page
over!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.