SpringBoot -- implementation of login verification code

Posted by mubashir on Thu, 09 Apr 2020 17:41:52 +0200

Today record the implementation of verification code, hope to help you!

First, let's look at the effect of the implementation:

 

The implementation of this verification code does not use too many plug-ins. If you don't speak much, you can directly use the code. You can take it.

The org.apache.commons.lang3.RandomUtils tool class is used in the middle. pom configuration is required:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>

1. Verification code class

package com.youyou.login.util.validatecode;

import lombok.Data;

/**
* Verification code class
*/
public class VerifyCode {
    private String code;
    private byte[] imgBytes;
    private long expireTime;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public byte[] getImgBytes() {
        return imgBytes;
    }
    public void setImgBytes(byte[] imgBytes) {
        this.imgBytes = imgBytes;
    }
    public long getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(long expireTime) {
        this.expireTime = expireTime;
    }

}

2. Verification code generation interface

package com.youyou.login.util.validatecode;

import java.io.IOException;
import java.io.OutputStream;

/**
* Verification code generation interface
*/
public interface IVerifyCodeGen {

/**
* Generate the verification code and return the code to write the picture in the os
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
String generate(int width, int height, OutputStream os) throws IOException;

/**
* Generate verification code object
*
* @param width
* @param height
* @return
* @throws IOException
*/
VerifyCode generate(int width, int height) throws IOException;
}

3. Verification code generation implementation class

package com.youyou.login.util.validatecode;

import com.youyou.util.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
* Verification code implementation class
*/
public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen {

private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class);

private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };

private static final int VALICATE_CODE_LENGTH = 4;

/**
* Set background color and size, interference line
*
* @param graphics
* @param width
* @param height
*/
private static void fillBackground(Graphics graphics, int width, int height) {
// Fill background
graphics.setColor(Color.WHITE);
//Set rectangular coordinates x y For 0
graphics.fillRect(0, 0, width, height);

// Add interference line
for (int i = 0; i < 8; i++) {
//Set random color algorithm parameters
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
}

/**
* Generate random characters
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
@Override
public String generate(int width, int height, OutputStream os) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//Set up JPEG format
ImageIO.write(image, "JPEG", os);
return randomStr;
}

/**
* Verification code generation
*
* @param width
* @param height
* @return
*/
@Override
public VerifyCode generate(int width, int height) {
VerifyCode verifyCode = null;
try (
//You don't need to close the flow manually if you put the initialization of the flow here
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
}

/**
* Set character color size
*
* @param g
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//Set up RGB Color algorithm parameters
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//Set font size, type
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//Set up x y coordinate
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
}

4. tool class

package com.youyou.util;

import java.awt.*;
import java.util.Random;

public class RandomUtils extends org.apache.commons.lang3.RandomUtils {

private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

private static Random random = new Random();

public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
}
return sb.toString();
}

public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
}
return sb.toString();
}

public static Color randomColor(int fc, int bc) {
int f = fc;
int b = bc;
Random random = new Random();
if (f > 255) {
f = 255;
}
if (b > 255) {
b = 255;
}
return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
}

public static int nextInt(int bound) {
return random.nextInt(bound);
}
}

After the above code, our verification code generation function has basically been implemented, and now we need a controller to call it.

@ApiOperation(value = "Verification Code")
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
try {
//Set length and width
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
String code = verifyCode.getCode();
LOGGER.info(code);
//take VerifyCode binding session
request.getSession().setAttribute("VerifyCode", code);
//Set response header
response.setHeader("Pragma", "no-cache");
//Set response header
response.setHeader("Cache-Control", "no-cache");
//Prevent buffering on the proxy side
response.setDateHeader("Expires", 0);
//Set response content type
response.setContentType("image/jpeg");
response.getOutputStream().write(verifyCode.getImgBytes());
response.getOutputStream().flush();
} catch (IOException e) {
LOGGER.info("", e);
}
}

Fix it! This is the end of background writing. Then some bloggers will say, "what's the good effect?"

OK, so let's move on to front-end coding.

Front end code:

<html>
<body>

<div>
<input id="code" placeholder="Verification Code" type="text" class=""
style="width:170px">
<!-- Verification code display -->
<img οnclick="javascript:getvCode()" id="verifyimg" style="margin-left: 20px;"/>
</div>

<script type="text/javascript">
getvCode();

/**
* Get verification code
* Write the verification code to the login.html page where id = verifyimg
*/
function getvCode() {
document.getElementById("verifyimg").src = timestamp("http://127.0.0.1:81/verifyCode");
}
//by url Add timestamp
function timestamp(url) {
var getTimestamp = new Date().getTime();
if (url.indexOf("?") > -1) {
url = url + "&timestamp=" + getTimestamp
} else {
url = url + "?timestamp=" + getTimestamp
}
return url;
};
</script>
</body>

</html>

Click the picture to change the verification code.

Effect:

 

Of course, the screenshot at the beginning of the article is the screenshot of my system, which requires everyone to develop the front-end according to their own situation.
Original link: https://blog.csdn.net/qq_37651267/article/details/99305573

Topics: Java Apache Javascript Lombok