The function of verification code: Usually, when logging in or registering a system, users will be required to enter verification code to distinguish user behavior from computer program behavior. The purpose is to prevent malicious registration, brute-force password cracking, etc.
Ideas for implementing verification codes: Use server to realize the function of randomly generating numbers and letters to form pictures, use jsp page to realize the function of displaying verification codes and user input verification codes, and then use server class to obtain the data input by the picture and user to determine whether the two data are consistent.
Code implementation
1. Write a server class randomly generated in numbers and English, source code:
package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class logcheck extends HttpServlet { public logcheck() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /*Core code of implementation*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); HttpSession session=request.getSession(); int width=60; int height=20; //Set the browser not to cache this image response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); //Create memory image and get the graphics context BufferedImage image=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); Graphics g=image.getGraphics(); /* * Generate random verification code* Character table that defines the verification code*/ String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] rands=new char[4]; for(int i=0;i<4;i++){ int rand=(int) (Math.random() *36); rands[i]=chars.charAt(rand); } /* * Generate image* Draw background*/ g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, width, height); /* * Randomly generate 120 interference points*/ for(int i=0;i<120;i++){ int x=(int)(Math.random()*width); int y=(int)(Math.random()*height); int red=(int)(Math.random()*255); int green=(int)(Math.random()*255); int blue=(int)(Math.random()*255); g.setColor(new Color(red,green,blue)); g.drawOval(x, y, 1, 0); } g.setColor(Color.BLACK); g.setFont(new Font(null, Font.ITALIC|Font.BOLD,18)); //Output different characters of verification code at different heights g.drawString(""+rands[0], 1, 17); g.drawString(""+rands[1], 16, 15); g.drawString(""+rands[2], 31, 18); g.drawString(""+rands[3], 46, 16); g.dispose(); //Paste the image to the client ServletOutputStream sos=response.getOutputStream(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); ImageIO.write(image, "JPEG", baos); byte[] buffer=baos.toByteArray(); response.setContentLength(buffer.length); sos.write(buffer); baos.close(); sos.close(); session.setAttribute("checkcode", new String(rands)); } public void init() throws ServletException { // Put your code here }} 2. Page used to display verification code :
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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%>"> <title>index</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"> --> </head> <body> <form action="yanzheng" method="post"> <input type="text" name="name" size="5" maxlength="4"> <a href="index.jsp"><img src="logcheck"></a><br><br> <input type="submit" value="submit"> </form> </body></html>
3. Used to check whether the entered verification code is correct:
package com;import java.io.IOException;import java.io.PrintWriter;import javax.jms.Session;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.servlet.http.HttpSession;public class yanzheng extends HttpServlet { public yanzheng() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /*Core Code*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String info=null; /*Get the input value*/ String value1=request.getParameter("name"); /*Get the image value*/ HttpSession session=request.getSession(); String value2=(String)session.getAttribute("checkcode"); /*Compare the two values (letters are case-insensitive)*/ if(value2.equalsIgnoreCase(value1)){ info="verification code input correct"; }else{ info="verification code input error"; } System.out.println(info); request.setAttribute("info", info); request.getRequestDispatcher("/login.jsp").forward(request, response); } public void init() throws ServletException { // Put your code here }}4. Display the input structure interface (whether the input verification code is correct):
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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%>"> <title>My JSP 'login.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"> --> </head> <body> <%=request.getAttribute("info") %> </body></html>5. Project structure and effect screenshots:
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.