工具及其技術(shù):
- vscode(對(duì),不用idea 也能開(kāi)發(fā)得特別爽)
- spring boot 2.0
- kapcha
1.添加依賴(lài):
在pom.xml中輸入依賴(lài):
<!-- kaptcha驗(yàn)證碼 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. 通過(guò)配置類(lèi)來(lái) 配置kaptcha
首先,新建kaptcha的config類(lèi):
import java.util.Properties;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
DefaultKaptcha defaultKaptcha = 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.textproducer.char.space", "5");
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);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
注意:
- 要用@Configuration注解來(lái)注冊(cè)這個(gè)配置文件
- defaultKaptcha 這個(gè)kaptcha類(lèi)的實(shí)例在spring 周期中為單例模式,注意命名(需要在conrtoller中用同名變量去獲得該bean的實(shí)例)
然后新建kaptchacontroller,用來(lái)得到驗(yàn)證碼圖片:
//KaptchaController.java
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class KaptchaContorller {
@Autowired
private Producer defaultKaptcha = null;
@RequestMapping("/kaptcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
// 告訴瀏覽器不要緩存,防止生成同樣的驗(yàn)證碼圖片
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");
// 返回信息為jpg
response.setContentType("image/jpeg");
// 生成驗(yàn)證碼
String capText = defaultKaptcha.createText();
// 將驗(yàn)證碼生成的文字保存到session 中,等待比對(duì)
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bufferedImage = defaultKaptcha.createImage(capText);
// 將圖片寫(xiě)到response中返回s
try {
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意事項(xiàng):
@Autowired
private Producer defaultKaptcha = null;
- Producer的變量名必須是kaptchaconfig.java中defaultKaptcha的實(shí)例名字;
- 每次在生成驗(yàn)證碼的時(shí)候,將驗(yàn)證碼的內(nèi)容寫(xiě)入到session中,然后下次判斷輸入驗(yàn)證碼是否正確的時(shí)候可以用session指定key來(lái)獲取判斷
生成驗(yàn)證碼圖片效果:
3. 驗(yàn)證碼校驗(yàn)
在controller 中,我們只需要拿出session中的驗(yàn)證碼值,跟post上來(lái)的結(jié)果做一遍比較,即可:
@RequestMapping(value = "/login")
public String login(HttpServletRequest request){
//獲取生成的驗(yàn)證碼
String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String inputCode = request.getParameter("kaptchaString");
if(inputCode==null){
return "error";
}
if(inputCode.equals(verifyCodeExpected)){
return "OK";
}else{
return "Error";
}
}
@RequestMapping("/")
public String index(){
return "forward:/index.html";
}
//index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測(cè)試kaptcha</title>
<script type="text/javascript">
function refresh() {
document.getElementById('kaptchaimg').src="/kaptcha";
}
</script>
</head>
<body>
<form action="/login" method="POST">
驗(yàn)證碼: <input type="text" placeholder="請(qǐng)輸入驗(yàn)證碼" name="kaptchaString">
<div class="item-input">
<img id="kaptchaimg"
onclick="refresh()" src="/kaptcha" />
</div>
<input type="submit" value="submit" />
</form>
</body>
</html>