一个用jsp+Servlet+jquery+ajax实现的验证码,及验证是否正确。供初学者学习交流。
效果图:
源代码:
validate.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %>"> 验证码
web.xml
validate /validate validate test.MyValidateServlet check /check check test.CheckServlet
ValidateCode.java
package util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.p_w_picpath.BufferedImage; import java.util.Random; public class ValidateCode { public static final int TYPE_NUM_ONLY = 0; public static final int TYPE_LETTER_ONLY = 1; public static final int TYPE_ALL_MIXED = 2; public static final int TYPE_NUM_UPPER = 3; public static final int TYPE_NUM_LOWER = 4; public static final int TYPE_UPPER_ONLY = 5; public static final int TYPE_LOWER_ONLY = 6; public static String generateTextCode(int type, int length, String exChars) { if (length <= 0) { return ""; } StringBuffer code = new StringBuffer(); int i = 0; Random r = new Random(); switch (type) { case 0: while (i < length) { int t = r.nextInt(10); if ((exChars == null) || (exChars.indexOf(t) < 0)) { code.append(t); i++; } } break; case 1: while (i < length) { int t = r.nextInt(123); if (((t >= 97) || ((t >= 65) && (t <= 90))) && ((exChars == null) || (exChars.indexOf((char) t) < 0))) { code.append((char) t); i++; } } break; case 2: while (i < length) { int t = r.nextInt(123); if (((t < 97) && ((t < 65) || (t > 90)) && ((t < 48) || (t > 57))) || ((exChars != null) && (exChars.indexOf((char) t) >= 0))) continue; code.append((char) t); i++; } break; case 3: while (i < length) { int t = r.nextInt(91); if (((t >= 65) || ((t >= 48) && (t <= 57))) && ((exChars == null) || (exChars.indexOf((char) t) < 0))) { code.append((char) t); i++; } } break; case 4: while (i < length) { int t = r.nextInt(123); if (((t >= 97) || ((t >= 48) && (t <= 57))) && ((exChars == null) || (exChars.indexOf((char) t) < 0))) { code.append((char) t); i++; } } break; case 5: while (i < length) { int t = r.nextInt(91); if ((t >= 65) && ((exChars == null) || (exChars.indexOf((char) t) < 0))) { code.append((char) t); i++; } } break; case 6: while (i < length) { int t = r.nextInt(123); if ((t >= 97) && ((exChars == null) || (exChars.indexOf((char) t) < 0))) { code.append((char) t); i++; } } } return code.toString(); } public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor) { BufferedImage bim = new BufferedImage(width, height, 1); Graphics g = bim.getGraphics(); g.setColor(backColor == null ? getRandomColor() : backColor); g.fillRect(0, 0, width, height); Random r = new Random(); if (interLine > 0) { int x = 0; int y = 0; int x1 = width; int y1 = 0; for (int i = 0; i < interLine; i++) { g.setColor(lineColor == null ? getRandomColor() : lineColor); y = r.nextInt(height); y1 = r.nextInt(height); g.drawLine(x, y, x1, y1); } } int fsize = (int) (height * 0.8D); int fx = height - fsize; int fy = fsize; g.setFont(new Font("Default", 0, fsize)); for (int i = 0; i < textCode.length(); i++) { fy = randomLocation ? (int) ((Math.random() * 0.3D + 0.6D) * height) : fy; g.setColor(foreColor == null ? getRandomColor() : foreColor); g.drawString(String.valueOf(textCode.charAt(i)), fx, fy); fx = (int) (fx + fsize * 0.9D); } g.dispose(); return bim; } public static BufferedImage generateImageCode(int type, int length, String exChars, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor) { String textCode = generateTextCode(type, length, exChars); BufferedImage bim = generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor); return bim; } private static Color getRandomColor() { Random r = new Random(); Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)); return c; } }
MyValidateServlet.java
package test; import java.awt.Color; import java.awt.p_w_picpath.BufferedImage; import java.io.IOException; import java.io.OutputStream; import javax.p_w_picpathio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import util.ValidateCode; public class MyValidateServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Pragma", "No-cache");// 设置响应头信息,告诉浏览器不要缓存此内容 resp.setHeader("Cache-Control", "no-cache"); resp.setDateHeader("Expire", 0); try { String textCode = ValidateCode.generateTextCode( ValidateCode.TYPE_ALL_MIXED, 6, null); BufferedImage p_w_picpath = ValidateCode.generateImageCode(textCode, 500, 100, 5, true, Color.GRAY, null, null); HttpSession session = req.getSession(true); session.setAttribute("captcha", textCode); resp.setContentType("p_w_picpath/jpeg"); OutputStream outputStream = resp.getOutputStream(); ImageIO.write(p_w_picpath, "jpeg", outputStream); } catch (Exception e) { e.printStackTrace(); } } }
CheckServlet.java
package test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class CheckServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;chartset=UTF-8"); req.setCharacterEncoding("UTF-8"); String input = (String) req.getParameter("input"); HttpSession sess = req.getSession(); String captcha = (String) sess.getAttribute("captcha"); PrintWriter out = resp.getWriter(); if(input.toUpperCase().equals(captcha.toUpperCase())){ out.print("{'success': true,'message': '验证码正确!'}"); }else{ out.print("{'success': false,'message': '验证码错误!'}"); } out.flush(); out.close(); } }