Implementation of login verification code under springmvc function example

  • 2020-06-15 08:32:34
  • OfStack

The general idea, in a nutshell, is to generate images in the background and save the image information in session, display the image in the front end, input the captCHA information, submit the form to the background, take out the captcha information stored in session, and check with the captcha information submitted in the form.

When clicking the captCHA image, jquery will re-request the method of generating captCHA image from the background to replace the image.

First of all, in the backend controller, there is such a method:

Path for http: / / localhost: 8888 / RiXiang_blog/login/captcha form, by writing image response access to this path.


  @RequestMapping(value = "/captcha", method = RequestMethod.GET)
  @ResponseBody
  public void captcha(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException 
  {
    CaptchaUtil.outputCaptcha(request, response);
  }

CaptchaUtil is a utility class that encapsulates captCHA image generation and session storage.

The code is as follows:


package com.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* @ClassName: CaptchaUtil 
* @Description:  The utility class for captchAs 
* @author  The unknown 
* @date 2016-5-7  In the morning 8:33:08 
* @version 1.0
 */
public final class CaptchaUtil
{
  private CaptchaUtil(){}
  
  /*
   *  Random character dictionary 
   */
  private 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' };
  
  /*
   *  The random number 
   */
  private static Random random = new Random();
  
  /*
   *  To obtain 6 A random number 
   */
  private static String getRandomString()
  {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < 6; i++)
    {
      buffer.append(CHARS[random.nextInt(CHARS.length)]);
    }
    return buffer.toString();
  }
  
  /*
   *  Gets the random number color 
   */
  private static Color getRandomColor()
  {
    return new Color(random.nextInt(255),random.nextInt(255),
        random.nextInt(255));
  }
  
  /*
   *  Returns the reverse of a color 
   */
  private static Color getReverseColor(Color c)
  {
    return new Color(255 - c.getRed(), 255 - c.getGreen(),
        255 - c.getBlue());
  }
  
  public static void outputCaptcha(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException 
  {

    response.setContentType("image/jpeg");

    String randomString = getRandomString();
    request.getSession(true).setAttribute("randomString", randomString);

    int width = 100;
    int height = 30;

    Color color = getRandomColor();
    Color reverse = getReverseColor(color);

    BufferedImage bi = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
    g.setColor(color);
    g.fillRect(0, 0, width, height);
    g.setColor(reverse);
    g.drawString(randomString, 18, 20);
    for (int i = 0, n = random.nextInt(100); i < n; i++) 
    {
      g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
    }

    //  into JPEG format 
    ServletOutputStream out = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(bi);
    out.flush();
  }
}

To get the captCHA image at the front end, write:


 ... 

<tr>
  <th>captcha</th>
  <td>
       <input type="text" id="captcha" name="captcha" class="text" maxlength="10" />
       <img id="captchaImage" src="captcha.form"/>
   </td>
 </tr>

img src write path, when the page loads will visit http: / / localhost: 8888 / RiXiang_blog/login/captcha form get photo.

The submission and login information validation of the form is not specified.

Click to change the js code of captcha as follows:


//  Replace verification code 
$('#captchaImage').click(function() 
{
  $('#captchaImage').attr("src", "captcha.form?timestamp=" + (new Date()).valueOf());
}); 

You can see that the time stamp is added as the argument, timestamp=" + (new Date()).valueOf (). By adding this parameter, you can re-access the background methods. Otherwise, the image cannot be refreshed.


Related articles: