This article shares the specific code for springmvc implementation verification code function display for your reference. The specific content is as follows
Let's look at the renderings first:
Ideas:
First of all, the verification code is a picture, a picture composed of random letters, numbers, patterns, etc., so this picture is definitely not fixed, it must be randomly created by the backend. The frontend uses IG's src to continuously access this manufacturing method.
Step 1: Front-end page writing
Login uses the ajax method, so it is used to call the click event. The image of the verification code is placed in the a tag to facilitate clicking and changing the verification code. The image is displayed using the src attribute of img. Because it is using springmvc, the background method is called to use action.
<form> <div id="login_tip"> Administrator login</div> <div><input type="text" id="user_code" name="user_code" placeholder="Please enter account"></div> <div><input type="password" id="user_account" name="user_account" placeholder="Please enter password"></div> <div id="btn_area"> <input type="text" id="VerificationCode" name="VerificationCode" placeholder="Please enter verification code"> <a href="javascript:void(0);" rel="external nofollow" onclick="VerificationCode()"> <img id="randCodeImage" src="VerificationCode/generate.action"/> </a> </div> <div style="float:left;"> <input type="button" name="button" id="sub_btn" onclick="login()" value="Login"/> </div> <div id="verification_Code"><b></b></div></form>
Step 2: Write JS code
Because login uses ajxa, backend login will verify some data, and if it is incorrect, it will return the data to the login page. Here we explain why a random number needs to be added after calling the method to generate the verification code. The random number here and the parameter name of this random number can be written at will, and the backend does not do any operation. This is a method to prevent the browser from getting cached when calling a same method, and the error in clicking on the image or verification code input will not be automatically refreshed and the image will be changed.
<script type="text/javascript"> function login(){ //This is to submit $.ajax({ type:'post', url:'Uase/query.action', //data:$('#loginInputForm').serialize(), data:{ 'user_code' : $("#user_code").val(), 'user_account' :$("#user_account").val(), 'VerificationCode':$("#VerificationCode").val(), }, dataType:'json', success:function(obj){ var rad = Math.floor(Math.random() * Math.pow(10, 8)); if(obj && obj.success=='true'){ window.location.href='Uase/login.action'; }else{ document.getElementById("verification_Code"). innerHTML =obj.msg; //uuuy is a random parameter name, which will not be processed by the backend. Its purpose is to avoid the browser reading the cached link $("#randCodeImage").attr("src", "VerificationCode/generate.action?uuuy="+rad); $("#VerificationCode").val("").focus(); // Clear and get focus} } } }); } /** *Verification code refresh*/ function VerificationCode(){ var rad = Math.floor(Math.random() * Math.pow(10, 8)); //uuuy is a random parameter name, which will not be processed by the backend. Its purpose is to avoid the browser reading the cached link $("#randCodeImage").attr("src", "VerificationCode/generate.action?uuuy="+rad); } </script>Step 3: Write the background Controller control class
The main method is VerificationCode, which uses some random number production methods and some auxiliary classes. You can use them all. Because I used verification codes that can change the type, I used a public tool class written by myself.
@RequestMapping("/VerificationCode")public class VerificationCodeController extends HttpServlet{ private static final long serialVersionUID = 1L; /** * The name used here to store the session*/ private static final String SESSION_KEY_OF_RAND_CODE = "randCode"; // todo to unify the constant/** * */ private static final int count = 200; /** * Define the graphic size (width) */ private static final int width = 105; /** * Define the graphic size (height) */ private static final int height = 35; /** * The length of the interference line = 1.414*lineWidth */ private static final int lineWidth = 1; @RequestMapping(value = "/generate", method = { RequestMethod.POST, RequestMethod.GET }) public void VerificationCode( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the page to not cache response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // response.setContentType("image/png"); // Create image in memory final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Get the graphics context final Graphics2D graphics = (Graphics2D) image.getGraphics(); // Set the background color graphics.setColor(Color.WHITE); // ---1.Color.WHITE is white graphics.fillRect(0, 0, width, height); // Fill diffraction// Set the border color//graphics.setColor(getRandColor(100, 200)); // ---2. This is to set the color with a numerical type. The color mode refers to the use of three primary colors: red, green, and blue. The other colors are obtained through the adjustment of the three colors. The values of these three primary colors are 0~255 graphics.drawRect(0, 0, width - 1, height - 1); final Random random = new Random(); // randomly generates interference lines, making the authentication code in the image not easy to be detected by other programs for (int i = 0; i < count; i++) { graphics.setColor(getRandColor(150, 200)); // ---3. final int x = random.nextInt(width - lineWidth - 1) + 1; // Ensure that it is drawn within the border final int y = random.nextInt(height - lineWidth - 1) + 1; final int xl = random.nextInt(lineWidth); final int yl = random.nextInt(lineWidth); graphics.drawLine(x, y, x + xl, y + yl); } // Take the randomly generated authentication code (4-digit number) final String resultCode = exctractRandCode(); for (int i = 0; i < resultCode.length(); i++) { // Display the authentication code in the image, and the color of the call function is the same. Maybe because the seed is too close, so you can only directly generate // graphics.setColor(new Color(20 + random.nextInt(130), 20 + random // .nextInt(130), 20 + random.nextInt(130))); // Set font color graphics.setColor(Color.BLACK); // Set font style //graphics.setFont(new Font("Arial Black", Font.ITALIC, 18)); graphics.setFont(new Font("Times New Roman", Font.BOLD, 24)); // Set characters, character spacing, upper margin System.out.print(resultCode.charAt(i)); graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26); } System.out.println("Direct output: "+resultCode); // Save the authentication code into SESSION request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode); // The image takes effect graphics.dispose(); // Output the image to the page ImageIO.write(image, "JPEG", response.getOutputStream()); } /** * @return Random code*/ private String exctractRandCode() { final String randCodeType = ResourceUtil.getRandCodeType(); int randCodeLength = Integer.parseInt(ResourceUtil.getRandCodeLength()); if (randCodeType == null) { return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength); } else { switch (randCodeType.charAt(0)) { case '1': return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength); case '2': return RandCodeImageEnum.LOWER_CHAR.generateStr(randCodeLength); case '3': return RandCodeImageEnum.UPPER_CHAR.generateStr(randCodeLength); case '4': return RandCodeImageEnum.LETTER_CHAR.generateStr(randCodeLength); case '5': return RandCodeImageEnum.ALL_CHAR.generateStr(randCodeLength); case '5': return RandCodeImageEnum.ALL_CHAR.generateStr(randCodeLength); default: return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength); } } } } /** * Description: Generate different colors according to the given number* @param This is to set the color with a numerical type. The color mode refers to the use of three primary colors: red, green, and blue. The values of these three primary colors are 0~255 through the adjustment of the three colors are obtained. The values of these three primary colors are 0~255. * @param This is to set the color with a numerical type. The color mode refers to the use of three primary colors: red, green, and blue. The values of these three primary colors are obtained by the adjustment of the three colors are 0~255. * @return Description: Return color*/ private Color getRandColor(int fc, int bc) { // Get the given range of random colors final Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } final int r = fc + random.nextInt(bc - fc); final int g = fc + random.nextInt(bc - fc); final int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * Verification code auxiliary class*/ enum RandCodeImageEnum { /** * Mixed string*/ ALL_CHAR("0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), // Remove the lowercase l and o characters that are not easy to distinguish; /** * Character */ LETTER_CHAR("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), /** * Lowercase letter */ LOWER_CHAR("abcdefghijklmnopqrstuvwxyz"), /** * Number */ NUMBER_CHAR("0123456789"), /** * UPPER_CHAR("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); /** * String to be generated*/ private String charStr; /** * @param charStr */ private RandCodeImageEnum(final String charStr) { this.charStr = charStr; } /** * Production random verification code* * @param codeLength * Length of verification code* @return verification code*/ public String generateStr(final int codeLength) { final StringBuffer sb = new StringBuffer(); final Random random = new Random(); final String sourceStr = getCharStr(); for (int i = 0; i < codeLength; i++) { sb.append(sourseStr.charAt(random.nextInt(sourseStr.length()))); } return sb.toString(); } /** * @return the {@link #charStr} */ public String getCharStr() { return charStr; } }}Step 4: Write common tool classes
/** * Project parameter tool class* */public class ResourceUtil { private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("sysConfig"); /** * Get the length of the random code* * @return The length of the random code*/ public static String getRandCodeLength() { return bundle.getString("randCodeLength"); } /** * Get the type of the random code* * @return The type of the random code*/ public static String getRandCodeType() { return bundle.getString("randCodeType"); }}Step 5: Config.properties
randCodeLength=4randCodeType=5
Step 6: Here you're done, you can try the effect