The generation and verification of front-end verification code images are implemented under SpringBoot for your reference. The specific content is as follows
1. Effect
Click the verification code to obtain the new verification code
2. Principle
The background generates a verification code picture and passes the picture to the front desk.
The background saves the verification code content in the session.
After entering the verification code in the front desk, it will be passed to the background and retrieved the verification code saved in the session for verification.
Note that the plain text of the verification code cannot be transmitted to the front end. The front-end content is transparent and unsafe. Verification code is used to prevent robots and not just people. If the verification code is clearly transmitted to the front end, it will be easily cracked.
3. Image generation
Verification code generation tool class RandomValidateCodeUtil
public class RandomValidateCodeUtil { public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";// key private String randString = "0123456789";// randomly generate a string with only numbers private String // private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";// randomly generate a string with only letters // private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";// Random generated strings of numbers and letters private int width = 95;// Image width private int height = 25;// Image height private int lineSize = 40;// Number of interference lines private int stringNum = 4;// Random generated number of characters private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class); private Random random random = new Random(); /** * Get font*/ private Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } /** * Get color*/ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /** * Generate random image*/ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // The BufferedImage class is an Image class with a buffer, and the Image class is a class used to describe image information BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// Generate Graphics object of Image object. You can perform various drawing operations on the image by modifying the object g.fillRect(0, 0, width, height);//Image size g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//Font size g.setColor(getRandColor(110, 133));//Font color//Draw interference lines for (int i = 0; i <= lineSize; i++) { drawLine(g); } //Draw randomString randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drawString(g, randomString, i); } logger.info(randomString); //Save the generated random string to session session.removeAttribute(RANDOMCODEKEY); session.setAttribute(RANDOMCODEKEY, randomString); g.dispose(); try { // Output the image in memory to the client through flowing form ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { logger.error("Failed to output the image in memory to the client through flow>>>> ", e); } } /** * Draw string*/ private String drawString(Graphics g, String randomString, int i) { g.setFont(getFont()); g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(randString .length()))); randomString += rand; g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(rand, 13 * i, 16); return randomString; } /** * Draw the interference line*/ private void drawLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /** * Get random characters*/ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); }}In the Controller call the method to generate verification code image and pass the image to the front end
/** * Generate verification code*/@RequestMapping(value = "/getVerify")public void getVerify(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("image/jpeg");//Set the corresponding type and tell the browser to output the content as an image response.setHeader("Pragma", "No-cache");//Set the response header information to tell the browser not to cache this content response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil(); randomValidateCode.getRandcode(request, response);//Output verification code image method} catch (Exception e) { logger.error("Failed to obtain verification code>>>> ", e); }} Front-end obtain verification code picture
html
<div> <div> <input type="tel" id="verify_input" placeholder="Please enter verification code" maxlength="4"> </div> </div> <div> <a href="javascript:void(0);" rel="external nofollow"> <img id="imgVerify" src="" onclick="getVerify(this);"> </a> </div></div>
js
//Get verification code function getVerify(obj){ obj.src = httpurl + "/sys/getVerify?"+Math.random();}Each time you click on the image and refresh the verification code interface for the first time, just call the getVerify() method.
4. Verification code verification
The front-end obtains the verification code entered by the user and passes it to the background for verification.
Background verification code
/** * Forgot password page verification code*/@RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")public boolean checkVerify(@RequestBody Map<String, Object> requestMap, HttpSession session) { try{ //Get random number from session String inputStr = requestMap.get("inputStr").toString(); String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY"); if (random == null) { return false; } if (random.equals(inputStr)) { return true; } else { return false; } }catch (Exception e){ logger.error("Verification code verification failed", e); return false; }}After background verification, return the front-end verification result true or false.
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.