springboot+vue集成Kaptcha实现验证码登录(完整简易版)

第一步 1、添加pom依赖

 <!-- 验证码 -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

第二步 2、添加一个 KaptchaConfig类,注意加上 @Configuration 注解 声明为配置类 全部跟我一样即可

package com.qingge.springboot.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Properties;
@Configuration
@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.put("kaptcha.border", "no");
        // 字体颜色
        properties.put("kaptcha.textproducer.font.color", "black");
        // 图片宽
        properties.put("kaptcha.image.width", "160");
        // 图片高
        properties.put("kaptcha.image.height", "40");
        // 字体大小
        properties.put("kaptcha.textproducer.font.size", "30");
        // 验证码长度
        properties.put("kaptcha.textproducer.char.space", "5");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

第三步 3、创建controller类,这里我命名为CheckController ,全部跟我一样即可

package com.qingge.springboot.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("/check")
public class CheckController {

    @Resource
    private DefaultKaptcha defaultKaptcha;

    public String getCheckCode() {
        return CheckCode;
    }

    public void setCheckCode(String checkCode) {
        CheckCode = checkCode;
    }

    private String CheckCode;

    @GetMapping
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);

            this.setCheckCode(verifyCode);
            BufferedImage challenge = defaultKaptcha.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


}

第四步 4、添加一个实体类,用于接收前端传过来的参数,跟据你自己的实际的来

package com.qingge.springboot.controller.dto;

import com.qingge.springboot.entity.Menu;
import lombok.Data;

import java.util.List;

/**
 * 接受前端登录请求的参数
 */
@Data
public class UserDTO {
    private String username;
    private String password;
    private String nickname;
    private String avatarUrl;
    private String token;
    private String role;
    private String check;
    private List<Menu> menus;
}

第五步 5、在你原有的登录接口上进行添加判断条件

 @Resource
    private CheckController checkCode;

    // 新增或者更新

    @PostMapping("/login")  //登入接口
    public Result login(@RequestBody UserDTO userDTO) {  //RequestBody将前端传过来的值映射成Java对象

        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)||StrUtil.isBlank(userDTO.getCheck())) {  // isBlank 判断是否为空
            return Result.error(Constants.CODE_400,"参数错误");
        }
//        String kaptchaCode = session.getAttribute("verifyCode") + "";
        String kaptchaCode = checkCode.getCheckCode();
        String rightCode = userDTO.getCheck();
        if (kaptchaCode.equals(rightCode)){
            UserDTO dto = userService.login(userDTO);
            return Result.success(dto);
        }else {
            return Result.error(Constants.CODE_401,"验证码输入有误");
        }
    }

第六步 6,用postman测试

是 ok 的。

第八步 8、前端登录界面添加图形验证码的容器,这里也是根据你自己实际情况来。

<div style="margin-top:35px;display:inline">
                    <el-form-item prop="check" style="display: inline-block;width: 220px;:inline-false;">
                        <el-input size="medium" prefix-icon="el-icon-message" placeholder="请输入验证码" v-model="user.check"
                                  style="margin-top: 20px;width: 240px"></el-input>
                    </el-form-item>
                </div>
                <div style=" position:absolute;top: 436px;display:inline;margin-left: 40px;">
                    <img alt="点击刷新" src='http://localhost:9090/check'
                         onclick="this.src='http://localhost:9090/check?d='+new Date()*1">
                </div>

 第九步 9、测试

是正常的,

 判断逻辑也是正常的,成功页面不好截图,因为成功了就跳转页面了。有问题给我留言吧!

最后,创作不易,如果对您有帮助,可以给我个点赞关注嘛,不定期更新优质文章,帮助您解决各类开发难题。

  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是使用Spring BootVue.js实现图片验证码登录验证的前后端代码: ## 后端代码(Spring Boot) ### 1. 引入依赖 在`pom.xml`中添加以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` ### 2. 创建验证码生成器 在`config`包下创建一个`KaptchaConfig`类,用于配置验证码生成器: ```java @Configuration public class KaptchaConfig { @Bean public Producer captchaProducer() { Properties properties = new Properties(); // 配置验证码生成器 // ... return new DefaultKaptcha(); } } ``` ### 3. 创建验证码接口 在`controller`包下创建一个`CaptchaController`类,用于生成验证码图片: ```java @RestController @RequestMapping("/captcha") public class CaptchaController { @Autowired private Producer captchaProducer; @GetMapping("/image") public void captchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { // 设置响应头信息,告诉浏览器返回的是图片 response.setContentType("image/jpeg"); // 配置验证码生成器 // ... // 生成验证码文本和图片 String captchaText = captchaProducer.createText(); BufferedImage captchaImage = captchaProducer.createImage(captchaText); // 将验证码文本存入session HttpSession session = request.getSession(); session.setAttribute("captchaText", captchaText); // 将验证码图片输出到响应流中 ServletOutputStream out = response.getOutputStream(); ImageIO.write(captchaImage, "jpeg", out); out.flush(); out.close(); } } ``` ### 4. 创建登录接口 在`controller`包下创建一个`LoginController`类,用于处理登录请求: ```java @RestController @RequestMapping("/login") public class LoginController { @PostMapping("/check") public boolean check(@RequestParam String captcha, HttpSession session) { // 获取session中存储的验证码文本 String captchaText = (String) session.getAttribute("captchaText"); // 比较用户输入的验证码和session中存储的验证码是否一致 return captchaText != null && captchaText.equalsIgnoreCase(captcha); } } ``` ## 前端代码(Vue.js) ### 1. 安装依赖 在项目目录下执行以下命令安装依赖: ```bash npm install axios vue-axios vue-qriously ``` ### 2. 创建组件 在`components`目录下创建一个`CaptchaLogin`组件,包含一个输入框、一个验证码图片和一个登录按钮: ```html <template> <div> <input type="text" v-model="captcha" placeholder="请输入验证码" /> <qriously :value="captchaImageUrl"></qriously> <button @click="login">登录</button> </div> </template> <script> import axios from "axios"; import VueAxios from "vue-axios"; import Qriously from "vue-qriously"; export default { name: "CaptchaLogin", components: { Qriously, }, data() { return { captcha: "", captchaImageUrl: "", }; }, created() { this.refreshCaptcha(); }, methods: { refreshCaptcha() { const captchaUrl = `/captcha/image?timestamp=${new Date().getTime()}`; this.captchaImageUrl = captchaUrl; }, login() { axios .post("/login/check", { captcha: this.captcha }) .then((response) => { if (response.data) { alert("登录成功"); } else { alert("验证码错误"); } this.refreshCaptcha(); }); }, }, mounted() { Vue.use(VueAxios, axios); }, }; </script> ``` ### 3. 在页面中使用组件 在需要登录验证的页面中使用`CaptchaLogin`组件: ```html <template> <div> <CaptchaLogin /> </div> </template> <script> import CaptchaLogin from "@/components/CaptchaLogin.vue"; export default { name: "LoginPage", components: { CaptchaLogin, }, }; </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值