//这个验证码画布生成是师兄写的,不是本人写的 1 package com.didinx.common; 2 3 import javax.imageio.ImageIO; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.awt.*; 10 import java.awt.image.BufferedImage; 11 import java.io.IOException; 12 import java.util.Random; 13 14 /** 15 * 验证码 16 */ 17 @WebServlet("/checkCodeServlet") 18 public class CheckCodeServlet extends HttpServlet { 19 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { 20 21 //服务器通知浏览器不要缓存 22 response.setHeader("pragma","no-cache"); 23 response.setHeader("cache-control","no-cache"); 24 response.setHeader("expires","0"); 25 26 //在内存中创建一个长80,宽30的图片,默认黑色背景 27 //参数一:长 28 //参数二:宽 29 //参数三:颜色 30 int width = 80; 31 int height = 30; 32 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 33 34 //获取画笔 35 Graphics g = image.getGraphics(); 36 //设置画笔颜色为灰色 37 g.setColor(Color.GRAY); 38 //填充图片 39 g.fillRect(0,0, width,height); 40 41 //产生4个随机验证码,12Ey 42 String checkCode = getCheckCode(); 43 //将验证码放入HttpSession中 44 request.getSession().setAttribute("code",checkCode); 45 46 //设置画笔颜色为黄色 47 g.setColor(Color.YELLOW); 48 //设置字体的小大 49 g.setFont(new Font("黑体",Font.BOLD,24)); 50 //向图片上写入验证码 51 g.drawString(checkCode,15,25); 52 53 //将内存中的图片输出到浏览器 54 //参数一:图片对象 55 //参数二:图片的格式,如PNG,JPG,GIF 56 //参数三:图片输出到哪里去 57 ImageIO.write(image,"PNG",response.getOutputStream()); 58 } 59 /** 60 * 产生4位随机字符串 61 */ 62 private String getCheckCode() { 63 String base = "0123456789ABCDEFGabcdefg"; 64 int size = base.length(); 65 Random r = new Random(); 66 StringBuffer sb = new StringBuffer(); 67 for(int i=1;i<=4;i++){ 68 //产生0到size-1的随机值 69 int index = r.nextInt(size); 70 //在base字符串中获取下标为index的字符 71 char c = base.charAt(index); 72 //将c放入到StringBuffer中去 73 sb.append(c); 74 } 75 return sb.toString(); 76 } 77 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 78 this.doGet(request,response); 79 } 80 }
验证码生成效果如图:
生成验证码后,可以用进行验证码校验,可以用ajax【blur(失去焦点事件)】也可以用同步提交,与表单同时提交,验证码校验程序如下,用的同步,与表单同步提交:
$("#loginForm").submit(function () { //id选择器获得页面输入的用户名 var username = $("#email").val(); //id选择器获得页面输入的密码 var password = $("#password").val(); //id选择器获得页面输入的验证码 var checkcode = $("#check").val(); $.post("/userServlet?methodName=login", { username: username, password: password, checkcode: checkcode //也可以用表单序列化 同样是id选择器 // var formData=$("#loginForm").serialize(); //可以在后台通过Map<String,String[]>map=request.getparameterMap获取 // }, function (result) { console.log(result); if (result.flag) { //alert("大帅哥"); location.href = "/index.html"; } else { //alert("小帅哥") $("#errorMsg").show().html(result.errorMsg) } }, "json"); return false; })
后台web程序如下:
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String checkcode = request.getParameter("checkcode"); String code = (String) request.getSession().getAttribute("code"); ResultInfo resultInfo = new ResultInfo(); if (!code.equalsIgnoreCase(checkcode)) { resultInfo.setFlag(false); resultInfo.setErrorMsg("验证码错误,请重新输入"); String str = JSON.toJSONString(resultInfo); response.getWriter().print(str); return; } UserService userService = new UserServiceImp(); User user = new User(); user.setUsername(username); user.setPassword(password); boolean outcome = userService.login(user); if (outcome) { resultInfo.setFlag(true); } else { resultInfo.setFlag(false); resultInfo.setErrorMsg("用户名或密码错误!请重新输入!"); } String str1 = JSON.toJSONString(resultInfo); response.getWriter().print(str1); }
②:通过鼠标点击验证码图片切换验证码:
//给图片绑定点击事件
<img src="/checkCodeServlet" onclick="changeimg(this)>;
//点击事件所调用的方法
funcion changeimg(img){
//通过获取点击时的当前时间并且拼接在url后面加载不同的图片(url参数不同,所以图片不同)
img.src="checkCodeServlet?data="+new Date.getTime();
}
原文地址:https://www.cnblogs.com/linsky/p/10356859.html
时间: 2024-10-09 13:45:08