這里只是貼前端部分代碼
頁面
<p style="margin-bottom: 0px" id="codeBox"> <img src="${rc.contextPath}/gif/getGifCode" id="codeImg" alt="驗證碼" width="146px" height="33px"> <a href="javascript:void(0);" id="changeCode">看不清,換一張</a> </p>
js部分,沒錯這個是不需要ajax刷新的。
后面的參數必須
①:帶時間參數
//刷新驗證碼 $(document).on('click','#changeCode',function(){ var img=document.getElementById("codeImg"); img.src=path+"/gif/getGifCode?"+new Date().getTime();
});
②:帶隨機數
//刷新驗證碼 $(document).on('click','#changeCode',function(){
var randomnum = Math.random(); var img=document.getElementById("codeImg"); img.src=path+"/gif/getGifCode?"+randomnum;
});
后台
/**
* 獲取驗證碼(Gif版本)
* @param response
*/
@RequestMapping(value={"/getGifCode","/changeGifCode"},method= RequestMethod.GET)
public void getGifCode(HttpServletResponse response, HttpServletRequest request){
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
/**
* gif格式動畫驗證碼
* 寬,高,位數(驗證碼位數)。
*/
Captcha captcha = new GifCaptcha(290,33,6);
//輸出
captcha.out(response.getOutputStream());
HttpSession session = request.getSession(true);
String id = request.getSession().getId();
//存入redis
redisService.setString("code"+id,captcha.text().toLowerCase());
//System.out.println("code"+id+"*****"+captcha.text().toLowerCase());
} catch (Exception e) {
System.err.println("獲取驗證碼異常:"+e.getMessage());
}
}
實現效果