广告
返回顶部
首页 > 资讯 > 精选 >springboot怎么集成easy-captcha实现图像验证码显示和登录
  • 817
分享到

springboot怎么集成easy-captcha实现图像验证码显示和登录

2023-07-05 21:07:09 817人浏览 安东尼
摘要

这篇文章主要介绍“SpringBoot怎么集成easy-captcha实现图像验证码显示和登录”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么集成easy-captcha实现图

这篇文章主要介绍“SpringBoot怎么集成easy-captcha实现图像验证码显示和登录”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么集成easy-captcha实现图像验证码显示和登录”文章能帮助大家解决问题。

1、easy-captcha简介

easy-captcha是生成图形验证码的Java类库,支持gif、中文、算术等类型,可用于JAVA WEB、JavaSE等项目

springboot怎么集成easy-captcha实现图像验证码显示和登录

2、添加依赖

<guava.version>20.0</guava.version><captcha.version>1.6.2</captcha.version><dependency>    <groupId>com.Google.guava</groupId>    <artifactId>guava</artifactId>    <version>${guava.version}</version></dependency><dependency>    <groupId>com.GitHub.whvcse</groupId>    <artifactId>easy-captcha</artifactId>    <version>${captcha.version}</version></dependency>

3、编写service层代码

@Servicepublic class CaptchaServiceImpl implements CaptchaService {        Cache<String, String> localCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build();    @Override    public void create(httpservletResponse response, String uuid) throws IOException {        response.setContentType("image/gif");        response.setHeader("Pragma", "No-cache");        response.setHeader("Cache-Control", "no-cache");        response.setDateHeader("Expires", 0);        //生成验证码        SpecCaptcha captcha = new SpecCaptcha(150, 40);        captcha.setLen(5);        captcha.setCharType(Captcha.TYPE_DEFAULT);        captcha.out(response.getOutputStream());        //保存到缓存        setCache(uuid, captcha.text());    }    @Override    public boolean validate(String uuid, String code) {        //获取验证码        String captcha = getCache(uuid);        //效验成功        if(code.equalsIgnoreCase(captcha)){            return true;        }        return false;    }    private void setCache(String key, String value){        localCache.put(key, value);    }    private String getCache(String key){        String captcha = localCache.getIfPresent(key);        //删除验证码        if(captcha != null){            localCache.invalidate(key);        }        return captcha;    }}

4、开发验证码接口

创建LoginController并提供生成验证码的方法

@Controller@AllArgsConstructorpublic class CaptchaController {    private CaptchaService captchaService;    @GetMapping("/captcha")    public void captcha(HttpServletResponse response, String uuid)throws IOException {        //uuid不能为空        AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);        //生成验证码        captchaService.create(response, uuid);    }}

5、前端Vue增加如何代码显示生成的验证码

<Motion :delay="200">  <el-fORM-item prop="verifyCode">    <el-input      clearable      v-model="ruleForm.verifyCode"      placeholder="验证码"      :prefix-icon="useRenderIcon(Line)"    >      <template v-slot:append>        <img          style="            vertical-align: middle;            height: 40px;            width: 100px;            cursor: pointer;          "          :src="captchaUrl"          @click="onRefreshCode"          alt=""        />      </template>    </el-input>  </el-form-item></Motion>

完整的登录页代码如下

<script setup lang="ts">import Motion from "./utils/motion";import { useRouter } from "vue-router";import { message } from "@/utils/message";import { loginRules } from "./utils/rule";import { useNav } from "@/layout/hooks/useNav";import type { FormInstance } from "element-plus";import { useLayout } from "@/layout/hooks/useLayout";import { useUserStoreHook } from "@/store/modules/user";import { bg, avatar, illustration } from "./utils/static";import { useRenderIcon } from "@/components/ReIcon/src/hooks";import { ref, Reactive, toRaw, onMounted, onBeforeUnmount } from "vue";import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";import { initRouter } from "@/router/utils";import { getUuid } from "@/utils/utils";import dayIcon from "@/assets/svg/day.svg?component";import darkIcon from "@/assets/svg/dark.svg?component";import Lock from "@iconify-icons/ri/lock-fill";import User from "@iconify-icons/ri/user-3-fill";import Line from "@iconify-icons/ri/shield-keyhole-line";import { getConfig } from "@/config";defineOptions({  name: "Login"});const router = useRouter();const loading = ref(false);const ruleFormRef = ref<FormInstance>();const captchaUrl = ref("");const { api } = getConfig();const { initStorage } = useLayout();initStorage();const { dataTheme, dataThemeChange } = useDataThemeChange();dataThemeChange();const { title } = useNav();const ruleForm = reactive({  username: "admin",  passWord: "admin123",  verifyCode: "",  uuid: ""});const onLogin = async (formEl: FormInstance | undefined) => {  loading.value = true;  if (!formEl) return;  await formEl.validate((valid, fields) => {    if (valid) {      useUserStoreHook()        .loginByUsername({ username: ruleForm.username, password: "admin123" })        .then(res => {          if (res.code == 200) {            // 获取后端路由            initRouter().then(() => {              router.push("/");              message("登录成功", { type: "success" });            });          }        });    } else {      loading.value = false;      return fields;    }  });};function onkeypress({ code }: KeyboardEvent) {  if (code === "Enter") {    onLogin(ruleFormRef.value);  }}function getCaptchaUrl() {  ruleForm.uuid = getUuid();  captchaUrl.value = `${Api}/captcha?uuid=${ruleForm.uuid}`;}function onRefreshCode() {  getCaptchaUrl();}onMounted(() => {  window.document.addEventListener("keypress", onkeypress);  getCaptchaUrl();});onBeforeUnmount(() => {  window.document.removeEventListener("keypress", onkeypress);});</script><template>  <div class="select-none">    <img :src="bg" class="wave" />    <div class="flex-c absolute right-5 top-3">      <!-- 主题 -->      <el-switch        v-model="dataTheme"        inline-prompt        :active-icon="dayIcon"        :inactive-icon="darkIcon"        @change="dataThemeChange"      />    </div>    <div class="login-container">      <div class="img">        <component :is="toRaw(illustration)" />      </div>      <div class="login-box">        <div class="login-form">          <avatar class="avatar" />          <Motion>            <h3 class="outline-none">{{ title }}</h3>          </Motion>          <el-form            ref="ruleFormRef"            :model="ruleForm"            :rules="loginRules"            size="large"          >            <Motion :delay="100">              <el-form-item                :rules="[                  {                    required: true,                    message: '请输入账号',                    trigger: 'blur'                  }                ]"                prop="username"              >                <el-input                  clearable                  v-model="ruleForm.username"                  placeholder="账号"                  :prefix-icon="useRenderIcon(User)"                />              </el-form-item>            </Motion>            <Motion :delay="150">              <el-form-item prop="password">                <el-input                  clearable                  show-password                  v-model="ruleForm.password"                  placeholder="密码"                  :prefix-icon="useRenderIcon(Lock)"                />              </el-form-item>            </Motion>            <Motion :delay="200">              <el-form-item prop="verifyCode">                <el-input                  clearable                  v-model="ruleForm.verifyCode"                  placeholder="验证码"                  :prefix-icon="useRenderIcon(Line)"                >                  <template v-slot:append>                    <img                      style="                        vertical-align: middle;                        height: 40px;                        width: 100px;                        cursor: pointer;                      "                      :src="captchaUrl"                      @click="onRefreshCode"                      alt=""                    />                  </template>                </el-input>              </el-form-item>            </Motion>            <Motion :delay="250">              <el-button                class="w-full mt-4"                size="default"                type="primary"                :loading="loading"                @click="onLogin(ruleFormRef)"              >                登录              </el-button>            </Motion>          </el-form>        </div>      </div>    </div>  </div></template><style scoped>@import url("@/style/login.CSS");</style><style lang="scss" scoped>:deep(.el-input-group__append, .el-input-group__prepend) {  padding: 0;}</style>

编译运行后端,同事运行点前端,可以看到登录页面。

关于“springboot怎么集成easy-captcha实现图像验证码显示和登录”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网精选频道,小编每天都会为大家更新不同的知识点。

--结束END--

本文标题: springboot怎么集成easy-captcha实现图像验证码显示和登录

本文链接: https://www.lsjlt.com/news/355400.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springboot怎么集成easy-captcha实现图像验证码显示和登录
    这篇文章主要介绍“springboot怎么集成easy-captcha实现图像验证码显示和登录”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么集成easy-captcha实现图...
    99+
    2023-07-05
  • Springboot+SpringSecurity怎么实现图片验证码登录
    本文小编为大家详细介绍“Springboot+SpringSecurity怎么实现图片验证码登录”,内容详细,步骤清晰,细节处理妥当,希望这篇“Springboot+SpringSecurity怎么实现图片验证码登录”文章能帮助大家解决疑惑...
    99+
    2023-06-30
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作