更新時(shí)間:2022-10-14 10:41:21 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1867次
登錄驗(yàn)證是大多數(shù)登錄系統(tǒng)都會(huì)用到的一個(gè)功能,它的驗(yàn)證方式也是有很多種,例如登錄驗(yàn)證碼,登錄驗(yàn)證條及拼圖拖動(dòng)塊等,這里講講輸入登錄驗(yàn)證碼的方式來實(shí)現(xiàn)的例子。首先,kaptcha這是一個(gè)開源的驗(yàn)證碼實(shí)現(xiàn)庫,利用這個(gè)庫可以非常方便的實(shí)現(xiàn)驗(yàn)證碼功能。
在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包,在該包下創(chuàng)建kaptcha配置類,配置驗(yàn)證碼的一些生成屬性。
KaptchaConfig.java
/**
* @author: yzy
* @Date: 2020/6/11 10:41
* @Description: 驗(yàn)證碼的配置
*/
@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;
}
}
新建一個(gè)控制器,提供系統(tǒng)登錄相關(guān)的API,在其中添加驗(yàn)證碼生成接口。
LoginController.java
/**
* @author: yzy
* @Date: 2020/6/11 10:58
* @Description: 登錄控制器
*/
@RestController
public class LoginController {
@Resource
private Producer producer;
/**
* @Description: 驗(yàn)證碼生成接口
* @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指定請(qǐng)求和響應(yīng)遵循的緩存機(jī)制
* no-store:用于防止重要的信息被無意的發(fā)布。在請(qǐng)求消息中發(fā)送將使得請(qǐng)求和響應(yīng)消息都不使用緩存。
* no-cache:指示請(qǐng)求或響應(yīng)消息不能緩存
*/
response.setHeader("Cache-Control","no-store,no-cache");
// 設(shè)置輸出流內(nèi)容格式為圖片格式.image/jpeg,圖片格式用于生成圖片隨機(jī)碼
response.setContentType("image/jpeg");
// 生成文字驗(yàn)證碼
String text = producer.createText();
// 生成圖片驗(yàn)證碼
BufferedImage image = producer.createImage(text);
// 保存驗(yàn)證碼到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);
}
}
測(cè)試接口
編譯成功后,訪問http://localhost:8010/swagger-ui.html,進(jìn)入swagger測(cè)試頁面,測(cè)試結(jié)果如圖:
這樣就大功告成了!
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743