Springboot实现验证码登录

网友投稿 389 2023-01-26


Springboot实现验证码登录

本文实例为大家分享了Springboot实现验证码登录的具体代码,供大家参考,具体内容如下

因为在项目中需要使用到验证码,我总结一下在项目中如何快速解决项目需求~验证码,下面推荐给大家速上手验证码的例子。

一、编写验证码工具类

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Random;

import javax.imageio.ImageIO;

/**

* @author zct

* @date 2018年2月6日

* @param

* @desc 图形验证码生成

*

*/

public class VerifyUtil {

// 验证码字符集

private static final char[] chars = {

'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',

'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',

'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

// 字符数量

private static final int SIZE = 4;

// 干扰线数量

private static final int LINES = 5;

// 宽度

private static final int WIDTH = 80;

// 高度

private static final int HEIGHT = 40;

// 字体大小

private static final int FONT_SIZE = 30;

/**

* 生成随机验证码及图片

* Object[0]:验证码字符串;

* Object[1]:验证码图片。

*/

public static Object[] createImage() {

StringBuffer sb = new StringBuffer();

// 1.创建空白图片

BufferedImage image = new BufferedImage(

WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

// 2.获取图片画笔

Graphics graphic = image.getGraphics();

// 3.设置画笔颜色

graphic.setColor(Color.LIGHT_GRAY);

// 4.绘制矩形背景

graphic.fillRect(0, 0, WIDTH, HEIGHT);

// 5.画随机字符

Random ran = new Random();

for (int i = 0; i

// 取随机字符索引

int n = ran.nextInt(chars.length);

// 设置随机颜色

graphic.setColor(getRandomColor());

// 设置字体大小

graphic.setFont(new Font(

null, Font.BOLD + Font.ITALIC, FONT_SIZE));

// 画字符

graphic.drawString(

chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);

// 记录字符

sb.append(chars[n]);

}

// 6.画干扰线

for (int i = 0; i < LINES; i++) {

// 设置随机颜色

graphic.setColor(getRandomColor());

// 随机画线

graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),

ran.nextInt(WIDTH), ran.nextInt(HEIGHT));

}

// 7.返回验证码和图片

return new Object[]{sb.toString(), image};

}

/**

* 随机取色

*/

public static Color getRandomColor() {

Random ran = new Random();

Color color = new Color(ran.nextInt(256),

ran.nextInt(256), ran.nextInt(256));

return color;

}

}

二、controller层使用

验证用户名和密码和验证码一致

/**

* 登录入口

*

* @param username 用户名

* @param password 密码

* @param code 验证码

* @param response 回调json数据 成功返回200,失败返回500

*/

@ApiOperation("登录")

@PostMapping("/login")

public void adminLoginByPasswword(@ApiParam("用户名") @RequestParam String username, @ApiParam("密码") @RequestParam String password, @ApiParam("验证码") @RequestParam String code, HttpServletResponse response,HttpServletRequest request) {

HttpSession session=request.getSession();

if(session.getAttribute("imageCode")==null){

renderFail(rSDDpidixWesponse, "重新获取验证码");

}else {

if(session.getAttribute("imageCode").toString().equalsIgnoreCase(code)){

Map user = adminService.checkAdminLogin(username, password);

if (user == null) {

renderFail(response, "登录失败");

} else {

renderSuccess(response, "登录成功");

}

}else {

renderFail(response, "验证码错误");

}

}

}

这里采用get请求获取验证码,获取验证码的接口如下

@ApiOperation("生成验证码")

@GetMapping("/getcode")

public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception{

HttpSession session=request.getSession();

//利用图片工具生成图片

//第一个参数是生成的验证码,第二个参数是生成的图片

Object[] objs = VerifyUtil.createImage();

//将验证码存入Session

session.setAttribute("imageCode",objs[0]);

//将图片输出给浏览器

BufferedImage image = (BufferedImage) objs[1];

response.setContentType("image/png");

OutputStream os = response.getOutputStream();

ImageIO.write(image, "png", os);

}

三、代码测试

这里用sprinhttp://gboot Swagger2测试

上面是get请求获取验证码,下面是登录验证,验证结果是成功的。

// 取随机字符索引

int n = ran.nextInt(chars.length);

// 设置随机颜色

graphic.setColor(getRandomColor());

// 设置字体大小

graphic.setFont(new Font(

null, Font.BOLD + Font.ITALIC, FONT_SIZE));

// 画字符

graphic.drawString(

chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);

// 记录字符

sb.append(chars[n]);

}

// 6.画干扰线

for (int i = 0; i < LINES; i++) {

// 设置随机颜色

graphic.setColor(getRandomColor());

// 随机画线

graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),

ran.nextInt(WIDTH), ran.nextInt(HEIGHT));

}

// 7.返回验证码和图片

return new Object[]{sb.toString(), image};

}

/**

* 随机取色

*/

public static Color getRandomColor() {

Random ran = new Random();

Color color = new Color(ran.nextInt(256),

ran.nextInt(256), ran.nextInt(256));

return color;

}

}

二、controller层使用

验证用户名和密码和验证码一致

/**

* 登录入口

*

* @param username 用户名

* @param password 密码

* @param code 验证码

* @param response 回调json数据 成功返回200,失败返回500

*/

@ApiOperation("登录")

@PostMapping("/login")

public void adminLoginByPasswword(@ApiParam("用户名") @RequestParam String username, @ApiParam("密码") @RequestParam String password, @ApiParam("验证码") @RequestParam String code, HttpServletResponse response,HttpServletRequest request) {

HttpSession session=request.getSession();

if(session.getAttribute("imageCode")==null){

renderFail(rSDDpidixWesponse, "重新获取验证码");

}else {

if(session.getAttribute("imageCode").toString().equalsIgnoreCase(code)){

Map user = adminService.checkAdminLogin(username, password);

if (user == null) {

renderFail(response, "登录失败");

} else {

renderSuccess(response, "登录成功");

}

}else {

renderFail(response, "验证码错误");

}

}

}

这里采用get请求获取验证码,获取验证码的接口如下

@ApiOperation("生成验证码")

@GetMapping("/getcode")

public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception{

HttpSession session=request.getSession();

//利用图片工具生成图片

//第一个参数是生成的验证码,第二个参数是生成的图片

Object[] objs = VerifyUtil.createImage();

//将验证码存入Session

session.setAttribute("imageCode",objs[0]);

//将图片输出给浏览器

BufferedImage image = (BufferedImage) objs[1];

response.setContentType("image/png");

OutputStream os = response.getOutputStream();

ImageIO.write(image, "png", os);

}

三、代码测试

这里用sprinhttp://gboot Swagger2测试

上面是get请求获取验证码,下面是登录验证,验证结果是成功的。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序之批量上传并压缩图片的实例代码
下一篇:接口自动化测试重要性(为什么要做接口自动化测试)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~