


How springboot integrates easy-captcha to realize image verification code display and login
1. Introduction to easy-captcha
easy-captcha is a Java class library that generates graphic verification codes. It supports gif, Chinese, arithmetic and other types, and can be used in Java Web, JavaSE and other projects.
2. Add dependencies
<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. Write service layer code
@Service public class CaptchaServiceImpl implements CaptchaService { /** * Local Cache 5分钟过期 */ 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. Develop verification code interface
Create LoginController and provide a method to generate verification codes
@Controller @AllArgsConstructor public 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. Front-end vue adds how to code display the generated verification code
<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 src="/static/imghw/default1.png" data-src="captchaUrl" class="lazy" style=" vertical-align: middle; height: 40px; width: 100px; cursor: pointer; " : @click="onRefreshCode" alt="" /> </template> </el-input> </el-form-item> </Motion>
The complete login page code is as follows
<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; } }); }; /** 使用公共函数,避免`removeEventListener`失效 */ 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 class="wave lazy" src="/static/imghw/default1.png" data-src="bg" : / alt="How springboot integrates easy-captcha to realize image verification code display and login" > <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 id="nbsp-title-nbsp">{{ 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 src="/static/imghw/default1.png" data-src="captchaUrl" class="lazy" style=" vertical-align: middle; height: 40px; width: 100px; cursor: pointer; " : @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>
Compile Run the backend, and a colleague runs the frontend and you can see the login page.
The above is the detailed content of How springboot integrates easy-captcha to realize image verification code display and login. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.
