java實現(xiàn)登錄驗證碼功能
本文實例為大家分享了java實現(xiàn)登錄驗證碼功能的具體代碼,供大家參考,具體內容如下
登錄驗證碼
登錄驗證是大多數(shù)登錄系統(tǒng)都會用到的一個功能,它的驗證方式也是有很多種,例如登錄驗證碼,登錄驗證條及拼圖拖動塊等,這里講講輸入登錄驗證碼的方式來實現(xiàn)的例子。首先,kaptcha這是一個開源的驗證碼實現(xiàn)庫,利用這個庫可以非常方便的實現(xiàn)驗證碼功能。
1.添加依賴
在pom文件下添加kaptcha依賴包
<!-- https://mvnrepository.com/artifact/com.github.axet/kaptcha -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.添加配置
新建config包,在該包下創(chuàng)建kaptcha配置類,配置驗證碼的一些生成屬性。
KaptchaConfig.java
/**
* @author: yzy
* @Date: 2020/6/11 10:41
* @Description: 驗證碼的配置
*/
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border","no");
properties.put("kaptcha.textproducer.font.color","black");
properties.put("kaptcha.textproducer.char.space","5");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.生成代碼
新建一個控制器,提供系統(tǒng)登錄相關的API,在其中添加驗證碼生成接口。
LoginController.java
/**
* @author: yzy
* @Date: 2020/6/11 10:58
* @Description: 登錄控制器
*/
@RestController
public class LoginController {
@Resource
private Producer producer;
/**
* @Description: 驗證碼生成接口
* @Author: yzy
* @Date: 2020/6/11 11:00
* @Param: response
* @Param: request
* @Return: void
* @Exception
*
*/
@RequestMapping(value = "/captcha.jpg",method = RequestMethod.GET)
public void captcha(HttpServletResponse response, HttpServletRequest request) {
/**
* Cache-Control指定請求和響應遵循的緩存機制
* no-store:用于防止重要的信息被無意的發(fā)布。在請求消息中發(fā)送將使得請求和響應消息都不使用緩存。
* no-cache:指示請求或響應消息不能緩存
*/
response.setHeader("Cache-Control","no-store,no-cache");
// 設置輸出流內容格式為圖片格式.image/jpeg,圖片格式用于生成圖片隨機碼
response.setContentType("image/jpeg");
// 生成文字驗證碼
String text = producer.createText();
// 生成圖片驗證碼
BufferedImage image = producer.createImage(text);
// 保存驗證碼到session中
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
ImageIO.write(image,"jpg",outputStream);
} catch (IOException e) {
e.printStackTrace();
}
IOUtils.closeQuietly(outputStream);
}
}
測試接口
編譯成功后,訪問http://localhost:8010/swagger-ui.html,進入swagger測試頁面,測試結果如圖:
這樣就大功告成了!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot?maven?打包插件介紹及注意事項說明
這篇文章主要介紹了springboot?maven?打包插件介紹及注意事項說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
SpringBoot--- SpringSecurity進行注銷權限控制的配置方法
這篇文章主要介紹了SpringBoot--- SpringSecurity進行注銷,權限控制,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
解析Idea為什么不推薦使用@Autowired進行Field注入
這篇文章主要介紹了Idea不推薦使用@Autowired進行Field注入的原因,網上文章大部分都是介紹兩者的區(qū)別,沒有提到為什么,當時想了好久想出了可能的原因,今天來總結一下2022-05-05

