文档详情

Java动态验证码.doc

发布:2018-04-21约7.13千字共7页下载文档
文本预览下载声明
实现的思路: 首先,需要创建一个Servlet。该Servlet通过字节型响应给客户端返回一个图片,该图片是通过JDK中Java 2D的类库来生成一个图片。图片的生成是依靠一个随机数来完成,然后将这个随机数写成图片格式。最后在Session将这个随机的字符串的状态保持住,以便在用户填写后进行对比。 其次,在需要加入验证码的JSP页面中,通过img src=生成验证码图片的URI/引入该图片。 最后,单用户填写完验证码后,提交到某一个Servlet中。在这个Servlet中,通过request.getParameter()方法获取用户添加的验证码,然后取出后与Session中生成的验证码进行对比,如果对比成功就表示通过,否则返回该页面给用户提示验证码错误的信息。 参考代码: 用来生成验证码图片的Servlet: package mon; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ValidateCodeServlet extends HttpServlet { // 验证码图片的宽度。 private int width = 60; // 验证码图片的高度。 private int height = 20; // 验证码字符个数 private int codeCount = 4; private int x = 0; // 字体高度 private int fontHeight; private int codeY; char[] codeSequence = { 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, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; /** * 初始化验证图片属性 */ public void init() throws ServletException { // 从web.xml中获取初始信息 // 宽度 String strWidth = this.getInitParameter(width); // 高度 String strHeight = this.getInitParameter(height); // 字符个数 String strCodeCount = this.getInitParameter(codeCount); // 将配置的信息转换成数值 try { if (strWidth != null strWidth.length() != 0) { width = Integer.parseInt(strWidth); } if (strHeight != null strHeight.length() != 0) { height = Integer.parseInt(strHeight); } if (strCodeCount != null strCodeCount.length() != 0) { codeCount = Integer.parseInt(strCodeCount); } } catch (NumberFormatException e) { } x = width / (codeCount + 1); fontHeight = height - 2; codeY = height - 4; } protected void service(HttpServletRequest req, HttpServletResponse resp) throws Se
显示全部
相似文档