springmvc 整合 kaptcha驗證碼
阿新 • • 發佈:2018-12-25
1.首先引入jar包,
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> <!--排除相容,防止下載不下來,下載後可以刪除--> <exclusions> <exclusion> <artifactId>javax.servlet-api</artifactId> <groupId>javax.servlet</groupId> </exclusion> </exclusions> </dependency>
2.在springmvc.xml中配置bean
<bean id="defaultKaptcha" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <!-- 驗證碼寬度 --> <prop key="kaptcha.image.width">110</prop> <!-- 驗證碼高度 --> <prop key="kaptcha.image.height">40</prop> <!-- 生成驗證碼內容範圍 --> <prop key="kaptcha.textproducer.char.string">0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ</prop> <!-- 驗證碼個數 --> <prop key="kaptcha.textproducer.char.length">4</prop> <!-- 是否有邊框 --> <prop key="kaptcha.border">no</prop> <!-- 邊框顏色 --> <prop key="kaptcha.border.color">105,179,90</prop> <!-- 邊框厚度 --> <prop key="kaptcha.border.thickness">1</prop> <!-- 驗證碼字型顏色 --> <prop key="kaptcha.textproducer.font.color">black</prop> <!-- 驗證碼字型大小 --> <prop key="kaptcha.textproducer.font.size">30</prop> <!-- 驗證碼所屬字型樣式 --> <prop key="kaptcha.textproducer.font.names">楷體</prop> <!-- 干擾線顏色 --> <prop key="kaptcha.noise.color">black</prop> <!-- 驗證碼文字字元間距 --> <prop key="kaptcha.textproducer.char.space">3</prop> <!-- 圖片樣式 :陰影--> <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop> </props> </constructor-arg> </bean> </property> </bean>
3,新建一個生成驗證碼的controller
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; import org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; @Controller public class CaptchaController { private Producer kaptchaProducer=null; @Autowired public void setCaptchaProducer(Producer kaptchaProducer) { this.kaptchaProducer = kaptchaProducer; } @RequestMapping("/kaptcha") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{ 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"); String capText = kaptchaProducer.createText(); //seesion的key request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); BufferedImage bi = kaptchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; } }
在頁面上,圖片的載入會訪問伺服器,所以將圖片的src設定成kaptcha就會找到這個controller,然後向頁面輸出驗證碼
3.jsp程式碼如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 引入 Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>線上圖書商城</title>
<%@ include file="/WEB-INF/inc/taglibs.jsp" %>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
#img {
position: absolute;
z-index: -5;
width: 100%;
max-width: 1320px;
height: 100%;
max-height: 600px;
}
</style>
</head>
<body>
<img id="img" src="statics/images/bg.jpg" />
<div>
<div>
<h1 class="text-center">線上圖書商城</h1>
<br><br>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-4 control-label">賬號</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="telphone" placeholder="請輸入名字">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-4 control-label">密碼</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="pass" placeholder="請輸入密碼">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-4 control-label">驗證碼</label>
<div class="col-sm-4">
<input type="text" name="verifyCode" placeholder="請輸入驗證碼"/>
<img src="kaptcha" id="kaptchaImage" title="看不清,點選換一張" onclick="changeVerifyCode()"><br><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="button" class="btn btn-default loginsubmit" >登入</button>
    
<button type="button" class="btn btn-default">註冊</button>
</div>
</div>
</form>
</div>
</div>
</body>
<script>
$(function () {
$(".loginsubmit").click(function(){
console.log("jquery起作用");
var telphone=$("#telphone").val();
var pass= $("#pass").val();
if(pass == "" || telphone == ""){
alert("賬號或密碼不能為空");
return;
}
$.ajax({
url:"login",
type:"post",
dataType:"json",
data:{"telphone":telphone,"pass":pass},
success:function(data){
if(data.code == '200'){
window.location="sysIndex";
}
},
error:function (data) {
console.log(data);
}
});
});
});
function changeVerifyCode() {
var time=new Date().getTime();
document.getElementById("kaptchaImage").src="kaptcha?d="+time;//為了不讓驗證碼快取,為了安全起見,需要次次都重新整理
}
</script>
</html>
由於每次點選圖片的時候,d的值不一樣,所以就相當與要載入一個新的驗證碼圖片,所以會再次訪問CaptchaController ,找到kaptcha.
4,提前登入的時候時候,用存在session的驗證碼和使用者輸入的驗證碼進行比對
@ResponseBody
@RequestMapping(value = "login",method = RequestMethod.POST)
public ReturnData loginInfo(@RequestParam(value = "telphone",required = true)String telphone,
@RequestParam(value = "pass",required = true)String pass, HttpServletRequest request){
ReturnData r = new ReturnData();
logger.info("進入login--post");
//這裡獲取seession裡的驗證碼
String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
logger.info("產生的驗證碼:"+kaptchaExpected);
Map<String,Object> map = new HashMap<>();
map.put("telphone",telphone);
map.put("pass",pass);
User user = userService.loginByphoneAndpass(map);
logger.info(user.toString());
if(user != null){
r.put("code","200");
r.put("msg","success");
r.put("user",user);
return r;
}
r.put("code","500");
r.put("msg","未找到使用者資訊");
return r;
}
5.驗證成功後進行登入.效果圖如下