前言:
關(guān)于kaptcha簡介以及spring整合kaptcha以及在Linux上驗(yàn)證碼顯示亂碼問題鳄厌,我在另一篇文章中已詳細(xì)講解,請參考:spring整合kaptcha驗(yàn)證碼惠窄。
本文將介紹springboot整合kaptcha的兩種方式谅辣。點(diǎn) 我 下載源碼。
歡迎大家關(guān)注我的公眾號 javawebkf前翎,目前正在慢慢地將簡書文章搬到公眾號稚配,以后簡書和公眾號文章將同步更新,且簡書上的付費(fèi)文章在公眾號上將免費(fèi)港华。
開發(fā)工具及技術(shù):
1道川、idea 2017
2、springboot 2.0.2
3、kaptcha
正式開始:
方式一:通過kaptcha.xml配置
1冒萄、用idea新建一個spring Initializr
2臊岸、添加kaptcha的依賴:
<!-- kaptcha驗(yàn)證碼 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
3、在resources下面新建kaptcha.xml尊流,內(nèi)容如下:
kaptcha.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 生成kaptcha的bean-->
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg type="java.util.Properties">
<!--設(shè)置kaptcha屬性 -->
<props>
<prop key = "kaptcha.border ">yes</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.textproducer.font.color">blue</prop>
<prop key="kaptcha.image.width">100</prop>
<prop key="kaptcha.image.height">50</prop>
<prop key="kaptcha.textproducer.font.size">27</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop>
<prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop>
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
<prop key="kaptcha.noise.color">black</prop>
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
<prop key="kaptcha.background.clear.from">185,56,213</prop>
<prop key="kaptcha.background.clear.to">white</prop>
<prop key="kaptcha.textproducer.char.space">3</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
</beans>
注:kaptcha.xml中的內(nèi)容其實(shí)就是和spring 整合kaptcha時spring-kaptcha.xml中內(nèi)容一樣帅戒,就是將kaptcha交給spring容器管理,設(shè)置一些屬性崖技,然后要用的時候直接注入即可逻住。
4、加載kaptcha.xml:
在springboot啟動類上加上@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"})
迎献,加了這個注解瞎访,springboot就會去加載kaptcha.xml文件。注意kaptcha.xml的路徑不要寫錯吁恍,classpath在此處是resources目錄装诡。
5、編寫controller用于生成驗(yàn)證碼:
CodeController.java
@Controller
public class CodeController {
@Autowired
private Producer captchaProducer = null;
@RequestMapping("/kaptcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//生成驗(yàn)證碼
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//向客戶端寫出
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
注:在這個controller徑注入剛剛kaptcha.xml中配置的那個bean践盼,然后就可以使用它生成驗(yàn)證碼鸦采,以及向客戶端輸出驗(yàn)證碼;記住這個類的路由,前端頁面驗(yàn)證碼的src需要指向這個路由咕幻。
6渔伯、新建驗(yàn)證碼比對工具類:
CodeUtil.java
public class CodeUtil {
/**
* 將獲取到的前端參數(shù)轉(zhuǎn)為string類型
* @param request
* @param key
* @return
*/
public static String getString(HttpServletRequest request, String key) {
try {
String result = request.getParameter(key);
if(result != null) {
result = result.trim();
}
if("".equals(result)) {
result = null;
}
return result;
}catch(Exception e) {
return null;
}
}
/**
* 驗(yàn)證碼校驗(yàn)
* @param request
* @return
*/
public static boolean checkVerifyCode(HttpServletRequest request) {
//獲取生成的驗(yàn)證碼
String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//獲取用戶輸入的驗(yàn)證碼
String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual");
if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) {
return false;
}
return true;
}
}
注:這個類用來比對生成的驗(yàn)證碼與用戶輸入的驗(yàn)證碼。生成的驗(yàn)證碼會自動加到session中肄程,用戶輸入的通過getParameter獲得锣吼。注意getParameter的key值要與頁面中驗(yàn)證碼的name值一致。
7蓝厌、使用驗(yàn)證碼:
①Controller
HelloWorld.java
@RestController
public class HelloWorld {
@RequestMapping("/hello")
public String hello(HttpServletRequest request) {
if (!CodeUtil.checkVerifyCode(request)) {
return "驗(yàn)證碼有誤玄叠!";
} else {
return "hello,world";
}
}
}
②頁面
hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function refresh() {
document.getElementById('captcha_img').src="/kaptcha?"+Math.random();
}
</script>
</head>
<body>
<form action="/hello" method="post">
驗(yàn)證碼: <input type="text" placeholder="請輸入驗(yàn)證碼" name="verifyCodeActual">
<div class="item-input">
<img id="captcha_img" alt="點(diǎn)擊更換" title="點(diǎn)擊更換"
onclick="refresh()" src="/kaptcha" />
</div>
<input type="submit" value="提交" />
</form>
</body>
</html>
注意:驗(yàn)證碼本質(zhì)是一張圖片,所以用<img >
標(biāo)簽拓提,然后通過src = "/kaptcha"
指向生成驗(yàn)證碼的那個controller的路由即可;通過onclick = “refresh()”
調(diào)用js代碼實(shí)現(xiàn)點(diǎn)擊切換功能;<input name = "verifyCodeActual ">
中要注意name的值读恃,在CodeUtil中通過request的getParameter()方法獲取用戶輸入的驗(yàn)證碼時傳入的key值就應(yīng)該和這里的name值一致。
8代态、測試:
輸入正確的驗(yàn)證碼
驗(yàn)證通過
輸入錯誤的驗(yàn)證碼
驗(yàn)證未通過
方式二:通過配置類來配置kaptcha
1寺惫、配置kaptcha
相比于方式一,一增二減蹦疑。
減:
①把kaptcha.xml刪掉
②把啟動類上的@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"})
注解刪掉
增:
①新建KaptchaConfig配置類西雀,內(nèi)容如下:
KaptchaConfig.java
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
DefaultKaptcha captchaProducer = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "30");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑");
Config config = new Config(properties);
captchaProducer.setConfig(config);
return captchaProducer;
}
}
注:這個類用來配置Kaptcha,就相當(dāng)于方式一的kaptcha.xml歉摧,把kaptcha加入IOC容器艇肴,然后return 回一個設(shè)置好屬性的實(shí)例腔呜,最后注入到CodeController中,在CodeController中就可以使用它生成驗(yàn)證碼再悼。要特別注意return captchaProducer;
與private Producer captchaProducer = null;
中captchaProducer
名字要一樣核畴,不然就加載不到這個bean。
2帮哈、測試:
輸入正確的驗(yàn)證碼:
驗(yàn)證通過
輸入錯誤的驗(yàn)證碼
驗(yàn)證未通過
為了說明兩次的驗(yàn)證碼是基于兩種方式生成的膛檀,方式一和方式二的驗(yàn)證碼我設(shè)置了不同的屬性,從圖片中可以看出兩次驗(yàn)證碼的顏色娘侍、干擾線咖刃、背景等都有不同。
總結(jié):
1憾筏、過程梳理:
不論是哪種方式嚎杨,都是先把kaptcha加入spring容器,即要有一個kaptcha的bean;再新建一個controller氧腰,把kaptcha的bean注入到controller中用于生成驗(yàn)證碼;然后需要有一個比對驗(yàn)證碼的工具類枫浙,在測試的controller中調(diào)用工具類進(jìn)行驗(yàn)證碼比對;最后在前端頁面只需要用一個<img src = "/生成驗(yàn)證碼的controller的路由">
即可獲取驗(yàn)證碼,通過給這個img標(biāo)簽加點(diǎn)擊事件就可實(shí)現(xiàn)“點(diǎn)擊切換驗(yàn)證碼”古拴。
2箩帚、與spring整合kaptcha對比
spring整合kaptcha也介紹了兩種方式,在web.xml中配置最簡潔黄痪,不需要寫生成驗(yàn)證碼的controller紧帕,在頁面中直接用src
指向web.xml中kaptcha的servlet 的<url-pattern >
的值即可。
springboot整合kaptcha的兩種方式都類似于spring整合kaptcha的第二種方式桅打,都是先配置bean是嗜,然后用controller生成驗(yàn)證碼,前端用src指向這個controller挺尾,不同之處在于:假如生成驗(yàn)證碼的controller路由為/xxx
鹅搪,那么spring 整合kaptcha時src = “xxx.jpg”
,springboot整合kaptcha時src = "/xxx"
遭铺。