本文實例為大家分享了java實現登錄驗證碼功能的具體代碼,供大家參考,具體內容如下
登錄驗證碼
登錄驗證是大多數登錄系統都會用到的一個功能,它的驗證方式也是有很多種,例如登錄驗證碼,登錄驗證條及拼圖拖動塊等,這里講講輸入登錄驗證碼的方式來實現的例子。首先,kaptcha這是一個開源的驗證碼實現庫,利用這個庫可以非常方便的實現驗證碼功能。
1.添加依賴
在pom文件下添加kaptcha依賴包
1
2
3
4
5
6
|
<!-- 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包,在該包下創建kaptcha配置類,配置驗證碼的一些生成屬性。
KaptchaConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * @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.生成代碼
新建一個控制器,提供系統登錄相關的API,在其中添加驗證碼生成接口。
LoginController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
/** * @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:用于防止重要的信息被無意的發布。在請求消息中發送將使得請求和響應消息都不使用緩存。 * 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測試頁面,測試結果如圖:
這樣就大功告成了!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/m0_45025997/article/details/106682638