This article will be fully explained from the front desk page to the back desk. Let’s take a look at it below.
1. Foreground code, image.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Get image verification code</title><script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.10.2.min.js"></script></head><body> <form action="##" method='post'> <input type="hidden" id="userId" name="userId" value=""> <div> <div> <input type="text" name='loginName' id="loginName" placeholder="username" value="" class='form-control'/> </div> </div> <div> <input type="password" autocomplete="off" id="pwd" name="pwd" placeholder="password" class='form-control'/> </div> </div> <div> <input id="validateCode" onblur="checkImg(this.value)" name="validateCode" type="text" placeholder="enter verification code"/> </div> <span><img id="codeValidateImg" onClick="javascript:flushValidateCode();"/></span> <p><a href="javascript:flushValidateCode();" >Change one</a></p> </div> <div> <span></span> </div> <div> <div> <input type="checkbox" name="remember" value="1" class='icheck-me' data-skin="square" data-color="blue" id="remember"> <label for="remember"> Remember me</label> </div> <input type="button" value="Login" onclick="javascript:submitForm();" class='btn btn-primary'> </div> </form><script type="text/javascript">$(document).ready(function() { flushValidateCode();//Refresh and generate verification code});/* Refresh and generate verification code*/function flushValidateCode(){var validateImgObject = document.getElementById("codeValidateImg");validateImgObject.src = "${pageContext.request.contextPath }/getSysManageLoginCode?time=" + new Date();}/* Verify that the verification code is entered correctly*/function checkImg(code){ var url = "${pageContext.request.contextPath}/checkimagecode"; $.get(url,{"validateCode":code},function(data){ if(data=="ok"){ alert("ok!") }else{ alert("error!") flushValidateCode(); } })}</script></body></html>2. Background code ImageGenController.java
package com.dufyun.springmvc.web.controller;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.dufy.javaweb.test.RandomValidateCode;@Controllerpublic class ImageGenController { @RequestMapping(value="/toImg") public String toImg(){ return "image/image"; } //Login to get the verification code @RequestMapping("/getSysManageLoginCode") @ResponseBody public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request) { response.setContentType("image/jpeg");// Set the corresponding type to 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.setHeader("Set-Cookie", "name=value; HttpOnly");// Set the HttpOnly property to prevent Xs attacks response.setDateHeader("Expire", 0); RandomValidateCode randomValidateCode = new RandomValidateCode(); try { randomValidateCode.getRandcode(request, response,"imagecode");// Output image method} catch (Exception e) { e.printStackTrace(); } return ""; } // Verification code verification@RequestMapping(value = "/checkimagecode") @ResponseBody public String checkTcode(HttpServletRequest request,HttpServletResponse response) { String validateCode = request.getParameter("validateCode"); String code = null; //1: Get the verification code information in the cookie Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("imagecode".equals(cookie.getName())) { code = cookie.getValue(); break; } } //1: Get the information of the session verification code //String code1 = (String) request.getSession().getAttribute(""); //2: Determine whether the verification code is correct if(!StringUtils.isEmpty(validateCode) && validateCode.equals(code)){ return "ok"; } return "error"; //I did not perform verification of letter size fuzzy processing here. If you are interested, you can try it! }}3. RandomValidateCode.java tool class to generate verification code
package com.dufy.javaweb.test;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class RandomValidateCode { private Random random = new Random(); private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";// Randomly generated string private int width = 80;// Picture width private int height = 26;// Picture height private int lineSize = 40;// Number of interference lines private int stringNum = 4;// Randomly generated characters/* * 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); } /* * 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)); } /** * Generate random image*/ public void getRandcode(HttpServletRequest request,HttpServletResponse response,String key) { // 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); g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18)); g.setColor(getRandColor(110, 133)); // Draw the interference line for (int i = 0; i <= lineSize; i++) { drawLine(g); } // Draw the random character String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drawString(g, randomString, i); } //1: Put the randomly generated verification code into the cookie Cookie cookie = new Cookie(key,randomString); response.addCookie(cookie); //2: Put the randomly generated verification code into the session String sessionid = request.getSession().getId(); request.getSession().setAttribute(sessionid+key, randomString); System.out.println("************" + randomString); //Summary: Both methods are good, //(1): Use cookies to send verification code to the front browser, which is not safe! Not recommended for use. //(2): Using session method can solve the problem that verification code is not sent to the browser, which is more secure, but if the number of users is too large, such storage method will put pressure on the server and affect the performance of the server. Not recommended for use. //This method is temporarily implemented here. The best way is to store the generated verification code in the cache used in the project and set the invalidation time, which can not only achieve security but also reduce the pressure on the server. g.dispose(); try { ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(image, "png", tmp); tmp.close(); Integer contentLength = tmp.size(); response.setHeader("content-length", contentLength + ""); response.getOutputStream().write(tmp.toByteArray());// Output the image in memory to the client in flow} catch (Exception e) { e.printStackTrace(); } finally{ try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e2) { e2.printStackTrace(); } } }} 4. Summary
The content of this article ends here. If you don’t understand the contents inside, you can leave a message to discuss. I hope the content of this article will be helpful to everyone's study and work.