ImageServlet.java
  1 package com.yu;
  2 
  3 import javax.servlet.http.HttpServlet;
  4 import javax.servlet.http.HttpServletRequest;
  5 import javax.servlet.http.HttpServletResponse;
  6 import javax.servlet.http.HttpSession;
  7 import javax.servlet.ServletException;
  8 import javax.servlet.ServletOutputStream;
  9 import javax.imageio.ImageIO;
 10 import java.io.IOException;
 11 import java.awt.image.BufferedImage;
 12 import java.awt.*;
 13 import java.util.Random;
 14 
 15 
 16 public class ImageServlet extends HttpServlet {
 17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 18         doGet(request, response);
 19     }
 20 
 21     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 22     }
 23 
 24     // 验证码图片的宽度。
 25     private int width = 60;
 26 
 27     // 验证码图片的高度。
 28     private int height = 20;
 29 
 30     // 验证码字符个数
 31     private int codeCount = 4;
 32 
 33     private int x = 0;
 34 
 35     // 字体高度
 36     private int fontHeight;
 37 
 38     private int codeY;
 39 
 40     char[] codeSequence = {'A''B''C''D''E''F''G''H''I''J',
 41             'K''L''M''N''O''P''Q''R''S''T''U''V''W',
 42             'X''Y''Z''0''1''2''3''4''5''6''7''8''9'};
 43 
 44     /**
 45      * 初始化验证图片属性
 46      */
 47     public void init() throws ServletException {
 48         // 从web.xml中获取初始信息
 49         // 宽度
 50         String strWidth = this.getInitParameter("width");
 51         // 高度
 52         String strHeight = this.getInitParameter("height");
 53         // 字符个数
 54         String strCodeCount = this.getInitParameter("codeCount");
 55         
 56         System.out.println("strWidth=="+strWidth+"strHeight=="+strHeight+"strCodeCount=="+strCodeCount);
 57 
 58         // 将配置的信息转换成数值
 59         try {
 60             if (strWidth != null && strWidth.length() != 0) {
 61                 width = Integer.parseInt(strWidth);
 62                 if (strHeight != null && strHeight.length() != 0) {
 63                     height = Integer.parseInt(strHeight);
 64                 }
 65                 if (strCodeCount != null && strCodeCount.length() != 0) {
 66                     codeCount = Integer.parseInt(strCodeCount);
 67                 }
 68             }
 69             }catch(NumberFormatException e){
 70 
 71             }
 72 
 73             x = width / (codeCount + 1);
 74             fontHeight = height - 2;
 75             codeY = height - 4;
 76 
 77         }
 78 
 79     protected void service(HttpServletRequest req, HttpServletResponse resp)
 80             throws ServletException, java.io.IOException {
 81 
 82         // 定义图像buffer
 83         BufferedImage buffImg = new BufferedImage(width, height,
 84                 BufferedImage.TYPE_INT_RGB);
 85         Graphics2D g = buffImg.createGraphics();
 86 
 87         // 创建一个随机数生成器类
 88         Random random = new Random();
 89 
 90         // 将图像填充为白色
 91         g.setColor(Color.WHITE);
 92         g.fillRect(00, width, height);
 93 
 94         // 创建字体,字体的大小应该根据图片的高度来定。
 95         Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
 96         // 设置字体。
 97         g.setFont(font);
 98 
 99         // 画边框。
100         g.setColor(Color.BLACK);
101         g.drawRect(00, width - 1, height - 1);
102 
103         // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
104         g.setColor(Color.cyan);
105         for (int i = 0; i < 160; i++) {
106             int x = random.nextInt(width);
107             int y = random.nextInt(height);
108             int xl = random.nextInt(12);
109             int yl = random.nextInt(12);
110             g.drawLine(x, y, x + xl, y + yl);
111         }
112 
113         // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
114         StringBuffer randomCode = new StringBuffer();
115         int red = 0, green = 0, blue = 0;
116 
117         // 随机产生codeCount数字的验证码。
118         for (int i = 0; i < codeCount; i++) {
119             // 得到随机产生的验证码数字。
120             String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
121             // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
122             red = random.nextInt(255);
123             green = random.nextInt(255);
124             blue = random.nextInt(255);
125             // 用随机产生的颜色将验证码绘制到图像中。
126             g.setColor(new Color(red, green, blue));
127             g.drawString(strRand, (i + 1* x, codeY);
128 
129             // 将产生的四个随机数组合在一起。
130             randomCode.append(strRand);
131         }
132         // 将四位数字的验证码保存到Session中。
133         HttpSession session = req.getSession();
134         session.setAttribute("validateCode", randomCode.toString());
135 
136         // 禁止图像缓存。
137         resp.setHeader("Pragma""no-cache");
138         resp.setHeader("Cache-Control""no-cache");
139         resp.setDateHeader("Expires"0);
140 
141         resp.setContentType("image/jpeg");
142 
143         // 将图像输出到Servlet输出流中。
144         ServletOutputStream sos = resp.getOutputStream();
145         ImageIO.write(buffImg, "jpeg", sos);
146         sos.close();
147     }
148 }

ResultServlet.java
 1 package com.yu;
 2 
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import javax.servlet.ServletException;
 7 import java.io.IOException;
 8 import java.io.PrintWriter;
 9 
10 /**
11  * Created by IntelliJ IDEA.
12  * User: Administrator
13  * Date: 2009-11-18
14  * Time: 21:25:44
15  * To change this template use File | Settings | File Templates.
16  */
17 public class ResultServlet extends HttpServlet {
18 
19 
20         public void doGet(HttpServletRequest request, HttpServletResponse response)
21                 throws ServletException, IOException {
22 
23             doPost(request, response);
24         }
25         public void doPost(HttpServletRequest request, HttpServletResponse response)
26                 throws ServletException, IOException {
27 
28             response.setContentType("text/html;charset=utf-8");
29             String validateC = (String) request.getSession().getAttribute("validateCode");
30             String veryCode = request.getParameter("c");
31             System.out.println(veryCode);
32             System.out.println(validateC);
33             PrintWriter out = response.getWriter();
34             veryCode=veryCode.toUpperCase();
35             if (veryCode == null || "".equals(veryCode)) {
36                 out.println("验证码为空");
37             } else {
38                 if (validateC.equals(veryCode)) {
39                     out.println("验证码正确");
40                 } else {
41                     out.println("验证码错误");
42                 }
43             }
44             out.flush();
45             out.close();
46         }
47 
48     }
49 
changeImg.js
 1 function changeImg() {
 2     var imgSrc = $("#imgObj");
 3     var src = imgSrc.attr("src");
 4     imgSrc.attr("src", chgUrl(src));
 5     //时间戳
 6     //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
 7     function chgUrl(url) {
 8         var timestamp = (new Date()).valueOf();
 9         urlurl = url.substring(017);
10         if ((url.indexOf("?">= 0)) {
11             urlurl = url + "&t=" + timestamp;
12         } else {
13             urlurl = url + "?t=" + timestamp;
14         }
15         return urlurl;
16     }
17 }
18 function isRightCode() {
19     var code = $("#veryCode").attr("value");
20 
21     $.ajax({
22         type:"POST",
23         url:"ResultServlet",
24         data:"c="+code,
25         success:callback
26     });
27 }
28 
29 function callback(data) {
30     $("#info").html(data);
31 }
32 
ajax.jsp
 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head><title>ajax</title>
 4     <script type="text/javascript" src="/js/jquery-1.2.6.js"></script>
 5     <script type="text/javascript" src="/js/changImage.js"></script>
 6 </head>
 7 <body>
 8  <input id="veryCode" name="veryCode" type="text"/>
 9         <img id="imgObj" alt="" src="ImageServlet"/>
10          <a href="#" onclick="changeImg()">换一张</a>
11         <input type="button" value="验证" onclick="isRightCode()"/>
12          <div id="info"></div> 
13 </body>
14 </html>
web.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 5           http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 6          version="2.5">
 7 
 8     <servlet>
 9         <servlet-name>AjaxServlet</servlet-name>
10         <servlet-class>com.yu.AjaxServlet</servlet-class>
11     </servlet>
12     <servlet>
13         <servlet-name>ImageServlet</servlet-name>
14         <servlet-class>com.yu.ImageServlet</servlet-class>
15         <init-param>
16             <param-name>width</param-name>
17             <param-value>80</param-value>
18         </init-param>
19         <init-param>
20             <param-name>height</param-name>
21             <param-value>25</param-value>
22         </init-param>
23         <init-param>
24             <param-name>codeCount</param-name>
25             <param-value>4</param-value>
26         </init-param>
27     </servlet>
28     <servlet>
29         <servlet-name>ResultServlet</servlet-name>
30         <servlet-class>com.yu.ResultServlet</servlet-class>
31     </servlet>
32     <servlet-mapping>
33         <servlet-name>AjaxServlet</servlet-name>
34         <url-pattern>/AjaxServlet</url-pattern>
35     </servlet-mapping>
36     <servlet-mapping>
37         <servlet-name>ImageServlet</servlet-name>
38         <url-pattern>/ImageServlet</url-pattern>
39     </servlet-mapping>
40     <servlet-mapping>
41         <servlet-name>ResultServlet</servlet-name>
42         <url-pattern>/ResultServlet</url-pattern>
43     </servlet-mapping>
44 </web-app>