springboot实现验证码
定义一个验证码的配置类VerificationCode,代码如下:
public class VerificationCode {
private int width = 100;// 生成验证码图片的宽度
private int height = 30;// 生成验证码图片的高度
private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
private Random random = new Random();
private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String text;// 记录随机字符串
/**
* 获取一个随意颜色
*
* @return
*/
private Color randomColor() {
int red = random.nextInt(150);
int green = random.nextInt(150);
int blue = random.nextInt(150);
return new Color(red, green, blue);
}
/**
* 获取一个随机字体
*
* @return
*/
private Font randomFont() {
String name = fontNames[random.nextInt(fontNames.length)];
int style = random.nextInt(4);
int size = random.nextInt(5) + 24;
return new Font(name, style, size);
}
/**
* 获取一个随机字符
*
* @return
*/
private char randomChar() {
return codes.charAt(random.nextInt(codes.length()));
}
/**
* 创建一个空白的BufferedImage对象
*
* @return
*/
private BufferedImage createImage() {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setColor(bgColor);// 设置验证码图片的背景颜色
g2.fillRect(0, 0, width, height);
return image;
}
public BufferedImage getImage() {
BufferedImage image = createImage();
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
g2.setColor(randomColor());
g2.setFont(randomFont());
float x = i * width * 1.0f / 4;
g2.drawString(s, x, height - 8);
}
this.text = sb.toString();
drawLine(image);
return image;
}
/**
* 绘制干扰线
*
* @param image
*/
private void drawLine(BufferedImage image) {
Graphics2D g2 = (Graphics2D) image.getGraphics();
int num = 5;
for (int i = 0; i < num; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g2.setColor(randomColor());
g2.setStroke(new BasicStroke(1.5f));
g2.drawLine(x1, y1, x2, y2);
}
}
public String getText() {
return text;
}
public static void output(BufferedImage image, OutputStream out) throws IOException {
ImageIO.write(image, "JPEG", out);
}
}
再用户表中添加verify_code字段,再数据库实现类中定义属性verifyCode,然后再UserController中定义得到验证码图片的方法,代码如下:
/**
* 得到验证码图片
* @param request
* @param resp
* @throws IOException
*/
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
VerificationCode code = new VerificationCode();
BufferedImage image = code.getImage();
String text = code.getText();
HttpSession session = request.getSession(true);
session.setAttribute("verify_code", text);
VerificationCode.output(image,resp.getOutputStream());
}
然后再登录方法中利用LambdaQueryWrapper进行查询判断,代码如下:
// 登录
@PostMapping("/login")
public Result<User> login(@RequestBody User user, HttpServletRequest request){//这只是传进来的user,并没有在数据库中进行查找
User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
if (request.getSession(true).getAttribute("verify_code")==null||!user.getVerifyCode().equalsIgnoreCase(request.getSession(true).getAttribute("verify_code").toString())){
return Result.error("-1","验证码错误");
}
if (res==null){
return Result.error("-1","用户名或密码错误");
}
return Result.success(res);
}
vue实现验证码登录页面
<template>
<div style="width: 100%;height: 100vh; background: linear-gradient(90deg,#3cadeb,#9c88ff);display: flex;justify-content: center;align-items: center">
<div style="width: 300px; height: 380px;box-shadow: 0 5px 15px rgba(0, 0, 0, .8); display: flex;justify-content: center;align-items: center;">
<el-form :model="form" size="normal" style="height: 100% ;width: 220px;" ref="form" :rules="rules">
<div style="width: 100%;height: 40px;margin-top:10px;line-height: 40px;text-align: center">
<span style="color: white;font-weight: 900;font-size: 30px;">Login</span>
</div>
<el-form-item style="margin-top: 50px" prop="username">
<el-input v-model="form.username" prefix-icon="el-icon-user-solid" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="form.password" prefix-icon="el-icon-lock" placeholder="请输入密码" show-password></el-input>
</el-form-item>
<el-form-item prop="verifyCode">
<el-col :span="16">
<el-input
v-model="form.verifyCode"
prefix-icon="el-icon-message"
placeholder="验证码"
></el-input>
</el-col>
<el-col :span="8">
<img class="verifyCodeImg" :src="imgUrl" alt="" @click="resetImg">
</el-col>
</el-form-item>
<el-form-item>
<el-button style="color: white; border-radius: 30px;width: 100%; height: 50px;background: linear-gradient(90deg,#3cadeb,#9c88ff);" @click="login">登录</el-button>
</el-form-item>
<el-form-item style="text-align: center; color: white;">
<a @click="toRegister" style="font-size: 16px;font-weight: 500;opacity: 0.8;text-decoration: underline">注册</a>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script>
import request from "@/utils/request";
export default {
name: "Login",
data(){
return{
user:{},
imgUrl:"http://localhost:8081/user/verifyCode?time="+new Date(),
form:{
verifyCode:''
},
rules: {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
],
}
}
},
created() {
sessionStorage.removeItem("user");
},
methods:{
toRegister(){
this.$router.push("/register")
},
resetImg(){
this.imgUrl = "http://localhost:8081/user/verifyCode?time="+new Date();
},
login(){
this.$refs['form'].validate((valid) => {
if (valid) {
request.post("/api/user/login",this.form).then(res => {
console.log(res);
if (res.code==='0'){
this.$message({
type: "success",
message: "登录成功"
})
console.log("res.date:"+res.data)
sessionStorage.setItem("user",JSON.stringify(res.data));//缓存用户信息
var userStr=sessionStorage.getItem("user",JSON.stringify(res.data));
this.user=JSON.parse(userStr)
if(this.user.role=='1'){
this.$router.push("/pandaGrowthCurve");//登录成功后的页面跳转
}else{
this.$router.push("/layout");//登录成功后的页面跳转
}
}else {
this.$message({
type: "error",
message: res.msg
})
}
})
} else {
console.log('error submit!!');
return false;
}
});
}
}
}
</script>
<style scoped>
</style>