自制验证码工具类(我的项目用到了springmvc)
jsp页面表单项:
jsp代码:
<li>
<span class="dis">验证码:</span>
<input type="text" name="yzm" maxlength="4" tabindex="1">
<img src="code/getImageValidateCode.action" alt="验证码" id="yzm">
<a class="look blue _changeCapcherButton" id="look" href="javascript:void(0);" οnclick="changeImage()">看不清?换一张</a>
</li>
有个坑:
若img元素的src值写成(多加一个/的话)
src="/code/getImageValidateCode.action"
则会出错:无法获取验证码
js代码:
<script type="text/javascript">
/* 提交表单 */
function test(){
$("form").trigger("submit");
}
/* 更新图片验证码 */
function changeImage(){
var src=$("#yzm").attr("src")+"?date="+new Date().getTime();
$("#yzm").attr("src",src);
}
</script>
在这次举例中: test()方法用不到,可忽略
点击看不清?换一张,或者刷新页面时,onClick事件中请求的路径
http://localhost:8080/yirenbao/code/getImageValidateCode.action?date=1502526110483?date=1502526526262?date=1502526541840?date=1502526596643?date=1502526598415?date=1502526621779?date=1502526623195?date=1502526631265
而我当前主页面的路径地址如图:
验证码工具类CodeUtils
package com.qx.utils;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.dsna.util.images.ValidateCode;
public class CodeUtils {
//图片验证码
public static void createCode(HttpSession session,HttpServletResponse response) throws IOException{
ValidateCode validateCode=new ValidateCode(105,38,4,20);
String code = validateCode.getCode();//验证码
response.setContentType("image/*");
ImageIO.write(validateCode.getBuffImg(), "jpeg", response.getOutputStream());
session.setAttribute("code", code);
}
//文字验证码
public static String createCode(){
ValidateCode validateCode=new ValidateCode(105,38,4,20);
String code=validateCode.getCode(); //验证码
return code;
}
}
注:把获取到验证码的值存到session中,是为了验证用户输入的验证码与实际产生的验证码是否相同用
ImageController:
package com.qx.sso.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.qx.utils.CodeUtils;
@Controller
@RequestMapping("/code")
public class ImageController {
@RequestMapping("/getImageValidateCode")
public void createCode(HttpSession session,HttpServletResponse response){
//创建验证码
//将验证码返回
//将验证码存放到session中
try {
CodeUtils.createCode(session, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}