ValidateCode.jar :https://mp.csdn.net/postedit/100535977
springmvc 後端
@Controller
public class User {
@RequestMapping("index")
public void captcharBuild(HttpServletRequest request, HttpServletResponse response) throws IOException {
//生成驗證碼
//1.創建驗證碼對象
/*
* ValidateCode
* 1.寬度
* 2.高度
* 3.驗證碼個數
* 4.干擾線條數
*/
ValidateCode code = new ValidateCode(200, 30, 4, 6);
code.getCode(); //獲取驗證碼
//2。獲取response對象
code.write(response.getOutputStream());
}
}
前端
<html>
<body>
<img id="imageDis" src=""/>
<button id="but" >更換圖片</button>
</body>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
document.getElementById("but").onclick=function(){
document.getElementById('imageDis').src="index?"+Math.random(); //index是請求路徑
}
</script>
</html>
看到這裏有人可能要問,src請求路徑,後面爲什麼要加隨機數參數,應爲你重複訪問一個url 瀏覽器會調用緩存,也就說,無論你怎麼更換圖片,他永遠都顯示第一張圖片,應爲後面的請求不會生效。所以在後面加一個隨機數,保證每次的請求url不一樣,每次都去請求生成新的圖片