package com.test.controller; import javax.imageio.ImageIO; import org.springframework.stereotype.Controller; |
页面代码
<input id="veryCode" name="veryCode" type="text"/>
<img id="imgObj" alt="" src="xuan/verifyCode"/>
<a href="#" onclick="changeImg()">换一张</a>
<input type="button" value="验证" onclick="isRightCode()"/>
<div id="info" style="color:red"></div>
js换一张
//请求 http://localhost:8080/xuan/verifyCode?timestamp=1510476930463
function changeImg(){
var imgSrc = $("#imgObj");
var src = imgSrc.attr("src");
imgSrc.attr("src",chgUrl(src));
}
//时间戳
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
function chgUrl(url){
var timestamp = (new Date()).valueOf();
urlurl = url.substring(0,17);
if((url.indexOf("&")>=0)){
urlurl = url + "×tamp=" + timestamp;
}else{
urlurl = url + "?timestamp=" + timestamp;
}
return urlurl;
}
js验证验证码对错
http://localhost:8080/resultServlet/validateCode
function isRightCode(){
var code = $("#veryCode").val();
$.ajax({
type:"POST",
url:"resultServlet/validateCode",
data : {
code : code,
},
success:callback
});
}
function callback(data){
$("#info").html(data);
}
@Controller
public class ResultServlet {
@RequestMapping(value="resultServlet/validateCode",method=RequestMethod.POST,produces={MediaType.APPLICATION_JSON_VALUE})
public void doPost(HttpServletRequest request, HttpServletResponse response,String code)throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String validateC = (String) request.getSession().getAttribute("validateCode");
/*String veryCode = request.getParameter("code");*/
PrintWriter out = response.getWriter();
String data = "";
if(code==null||"".equals(code)){
out.println("验证码为空");
data="0";
}else{
if(validateC.equalsIgnoreCase(code)){
out.println("验证码正确");
data="1";
}else{
out.println("验证码错误");
data="2";
}
}
out.flush();
out.close();
}
}