更新時間:2022-10-14 10:41:21 來源:動力節點 瀏覽2027次
登錄驗證是大多數登錄系統都會用到的一個功能,它的驗證方式也是有很多種,例如登錄驗證碼,登錄驗證條及拼圖拖動塊等,這里講講輸入登錄驗證碼的方式來實現的例子。首先,kaptcha這是一個開源的驗證碼實現庫,利用這個庫可以非常方便的實現驗證碼功能。
在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>
新建config包,在該包下創建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;
}
}
新建一個控制器,提供系統登錄相關的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:用于防止重要的信息被無意的發布。在請求消息中發送將使得請求和響應消息都不使用緩存。
* 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測試頁面,測試結果如圖:
這樣就大功告成了!
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習