Servlet登录验证码
jopen
10年前
本文是收集加整理
Servlet代码:
package artshell; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * @see http://ewf-momo.iteye.com/blog/1678955 */ @WebServlet("/ConfirmCode") public class LoginConfirmCode extends HttpServlet { private static final long serialVersionUID = -7581060780017197844L; public static Random random = new Random(); // 验证码字符集 public static final char[] CHARS = { '1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' }; public LoginConfirmCode() { super(); } // 从字符集中得到随机字符串 public static String getRandomChars() { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 6; i++) { buffer.append(CHARS[random.nextInt(CHARS.length)]); } return buffer.toString(); } // 得到随机颜色 public static Color getRandomColor() { return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } // 得到随机颜色的反色 public static Color getReverseColor(Color c) { return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue()); } public void init(ServletConfig config) throws ServletException { super.init(); } public void destroy() { super.destroy(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应类型 response.setContentType("image/jpeg"); // 让浏览器不保存缓存,目的是防止刷新验证码时得到与先前相同验证码 response.setHeader("Cache-Control", "no-cache"); // 得到随机字符串 String randomChars = getRandomChars(); // 把随机数存到Session里面,便于等下比较 HttpSession session = request.getSession(); session.setAttribute("ConfirmCode", randomChars); // 得到随机颜色 Color color = getRandomColor(); // 得到随机颜色的反色 Color reverse = getReverseColor(color); // 在内存中创建图像,width=80,height=20 BufferedImage image = new BufferedImage(85, 30, BufferedImage.TYPE_INT_RGB); // 得到图像绘制类对象 Graphics g = image.getGraphics(); // 设置验证码的字体种类、样式、字号 g.setFont(new Font(Font.SANS_SERIF, Font.LAYOUT_RIGHT_TO_LEFT, 16)); // 设置字体颜色 g.setColor(color); // 填充一个矩形 g.fillRect(0, 0, 90, 30); // 设置矩形的填充颜色 g.setColor(reverse); // 绘制字符串 g.drawString(randomChars, 10, 20); // 随机产生验证码上的干扰线 for (int i = 0, n = random.nextInt(100); i < n; i++) { g.drawRect(random.nextInt(100), random.nextInt(30), random.nextInt(2), random.nextInt(2)); } // 关闭Graphics 对象,释放此图形的上下文以及它使用的所有系统资源 g.dispose(); // 得到字节输出流对象 ServletOutputStream out = response.getOutputStream(); // 将图像输出到页面 ImageIO.write(image, "JPEG", out); out.flush(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
前端页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <base href="<%=basePath%>>" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Insert title here</title> <script type="text/javascript"> function changeValidateCode(obj) { /*每次请求用当前时间作为参数,防止浏览器使用缓存数据,如果不采取这种方法,也可以把页面设置为不缓存*/ var timeNow = new Date().getTime(); obj.src = "ConfirmCode?time=" + timeNow; } </script> </head> <body> <form action="CheckLogin" method="post"> <table border="1"> <tr> <td>用户名:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="userpwd" /></td> </tr> <tr> <td>验证码:</td> <td><input type="text" name="code" size="8"/><img src="ConfirmCode" onclick="changeValidateCode(this)" alt="点击图像刷新验证码" /></td> </tr> <tr> <td><input type="submit" value="提交" /></td> <td><input type="reset" value="重置"/></td> </tr> </table> </form> </body> </html>