jsp servlet验证码


制作图形验证码关键在于编写生成图形的Servlet

[java]  view plain copy
  1. package com.petrochina.servlet;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.image.BufferedImage;  
  7. import java.io.IOException;  
  8. import java.util.Random;  
  9.   
  10. import javax.imageio.ImageIO;  
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15. import javax.servlet.http.HttpSession;  
  16.   
  17. public class AuthImg extends HttpServlet {  
  18.   
  19.     // 设置图形验证码中字符串的字体和大小  
  20.     private Font myFont = new Font("Arial Black", Font.PLAIN, 16);  
  21.   
  22.     @Override  
  23.     public void init() throws ServletException {  
  24.         super.init();  
  25.     }  
  26.   
  27.     // 生成随机颜色  
  28.     Color getRandColor(int fc, int bc) {  
  29.         Random random = new Random();  
  30.         if (fc > 255)  
  31.             fc = 255;  
  32.         if (bc > 255)  
  33.             bc = 255;  
  34.         int r = fc + random.nextInt(bc - fc);  
  35.         int g = fc + random.nextInt(bc - fc);  
  36.         int b = fc + random.nextInt(bc - fc);  
  37.         return new Color(r, g, b);  
  38.     }  
  39.   
  40.     @Override  
  41.     public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  42.   
  43.         // 阻止生成的页面内容被缓存,保证每次重新生成随机验证码  
  44.         response.setHeader("Pragma""No-cache");  
  45.         response.setHeader("Cache-Control""no-cache");  
  46.         response.setDateHeader("Expires"0);  
  47.         response.setContentType("image/jpeg");  
  48.         // 指定图形验证码图片的大小  
  49.         int width = 100, height = 20;  
  50.         // 生成一张新图片  
  51.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  52.         // 在图片中绘制内容  
  53.         Graphics g = image.getGraphics();  
  54.         Random random = new Random();  
  55.         g.setColor(getRandColor(200250));  
  56.         g.fillRect(11, width - 1, height - 1);  
  57.         g.setColor(new Color(102102102));  
  58.         g.drawRect(00, width - 1, height - 1);  
  59.         g.setFont(myFont);  
  60.         // 随机生成线条,让图片看起来更加杂乱  
  61.         g.setColor(getRandColor(160200));  
  62.         for (int i = 0; i < 155; i++) {  
  63.             int x = random.nextInt(width - 1);// 起点的x坐标  
  64.             int y = random.nextInt(height - 1);// 起点的y坐标  
  65.             int x1 = random.nextInt(6) + 1;// x轴偏移量  
  66.             int y1 = random.nextInt(12) + 1;// y轴偏移量  
  67.             g.drawLine(x, y, x + x1, y + y1);  
  68.         }  
  69.         // 随机生成线条,让图片看起来更加杂乱  
  70.         for (int i = 0; i < 70; i++) {  
  71.             int x = random.nextInt(width - 1);  
  72.             int y = random.nextInt(height - 1);  
  73.             int x1 = random.nextInt(12) + 1;  
  74.             int y1 = random.nextInt(6) + 1;  
  75.             g.drawLine(x, y, x - x1, y - y1);  
  76.         }  
  77.   
  78.         // 该变量用来保存系统生成的随机字符串  
  79.         String sRand = "";  
  80.         for (int i = 0; i < 6; i++) {  
  81.             // 取得一个随机字符  
  82.             String tmp = getRandomChar();  
  83.             sRand += tmp;  
  84.             // 将系统生成的随机字符添加到图形验证码图片上  
  85.             g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));  
  86.             g.drawString(tmp, 15 * i + 1015);  
  87.         }  
  88.   
  89.         // 取得用户Session  
  90.         HttpSession session = request.getSession(true);  
  91.         // 将系统生成的图形验证码添加  
  92.         session.setAttribute("rand", sRand);  
  93.         g.dispose();  
  94.         // 输出图形验证码图片  
  95.         ImageIO.write(image, "JPEG", response.getOutputStream());  
  96.   
  97.     }  
  98.   
  99.     // 随机生成一个字符  
  100.     private String getRandomChar() {  
  101.         int rand = (int) Math.round(Math.random() * 2);// 将0~2的小数四舍五入生成整数  
  102.         long itmp = 0;  
  103.         char ctmp = '/u0000';  
  104.         // 根据rand的值来决定是生成一个大写字母、小写字母和数字  
  105.         switch (rand) {  
  106.         // 生成大写字母的情形  
  107.         case 1:  
  108.             itmp = Math.round(Math.random() * 25 + 65);  
  109.             ctmp = (char) itmp;  
  110.             return String.valueOf(ctmp);  
  111.             // 生成小写字母  
  112.         case 2:  
  113.             itmp = Math.round(Math.random() * 25 + 97);  
  114.             ctmp = (char) itmp;  
  115.             return String.valueOf(ctmp);  
  116.             // 生成数字  
  117.         default:  
  118.             itmp = Math.round(Math.random() * 9);  
  119.             return String.valueOf(itmp);  
  120.         }  
  121.     }  
  122. }  
  

在web.xml中添加Servlet配置

[xhtml]  view plain copy
  1. <!-- 生成验证码 -->  
  2. <servlet>  
  3.     <servlet-name>authImg</servlet-name>  
  4.     <servlet-class>com.petrochina.servlet.AuthImg</servlet-class>  
  5. </servlet>  
  6. <servlet-mapping>  
  7.     <servlet-name>authImg</servlet-name>  
  8.     <url-pattern>/authImg</url-pattern>  
  9. </servlet-mapping>  

注册页面regist.jsp

[xhtml]  view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6. <title>注册页面</title>  
  7. <mce:script type="text/javascript" src="js/jquery.1.4.2.js" mce_src="js/jquery.1.4.2.js"></mce:script>  
  8. <mce:script type="text/javascript"><!--  
  9. //刷新验证码  
  10. function refresh()  
  11. {  
  12. document.getElementById("authImg").src="authImg?now="+new Date();//使用时间作为参数避免浏览器从缓存取图片  
  13. }  
  14. // --></mce:script>  
  15. </head>  
  16. <body>  
  17. <form action="registe.action" method="post" id="registe">  
  18. <table>  
  19.     <caption><h2>用户注册</h2></caption>  
  20.     <tr>  
  21.         <td>用 户 名:</td><td><input type="text" name="username" id="username"/></td>  
  22.     </tr>  
  23.     <tr>  
  24.         <td>密  码:</td><td><input type="text" name="password" id="password"/> </td>  
  25.     </tr>  
  26.     <tr>  
  27.         <td>确认密码:</td><td><input type="text" name="chkpassword"/> </td>  
  28.     </tr>  
  29.     <tr>  
  30.         <td>Email:</td><td><input type="text" name="email"/> </td>  
  31.     </tr>  
  32.     <tr>  
  33.         <td>验证码:</td><td valign="bottom"><input type="text" name="vercode" size="10"/> <img alt="" src="authImg" mce_src="authImg" id="authImg" align="absmiddle"><a href="#" mce_href="#" onclick="refresh()"><span style="font-size:12px" mce_style="font-size:12px">刷新验证码</span></a></td>  
  34.     </tr>  
  35.     <tr>  
  36.         <td colspan="2"><input type="submit" value="提交"/><input type="reset" value="重填"/></td>  
  37.     </tr>  
  38. </table>  
  39. </form>  
  40. </body>  
  41. </html>  

后台RegistAction

[java]  view plain copy
  1. @Override  
  2.     public String execute() throws Exception {  
  3.         Map session = ActionContext.getContext().getSession();  
  4.         String ver2 = (String) session.get("rand");  
  5.         session.put("rand"null);  
  6.         // 判断验证码是否正确  
  7.         if (vercode.equals(ver2)) {  
  8.             if (userManager.validName(username)) {  
  9.                 if (userManager.addUser(username, password, email) > 0)  
  10.                     return SUCCESS;  
  11.                 else  
  12.                     addActionError("注册失败,请重试!");  
  13.             } else {  
  14.                 addActionError("该用户名已存在,请重新输入!");  
  15.             }  
  16.         } else {  
  17.             addActionError("验证码不匹配,请重新输入");  
  18.         }  
  19.         return INPUT;  
  20.   
  21.     }  

结果如下:

到这里就完成了。但是今天在FireFox3.6下使用firedebug调试时发现会再请求一次验证码,这样导致session中的验证码刷新之后和页面上的不一致,问题截图如下:

在关闭firedebug的情况下只请求一次验证码,在IE下也正常,寻思可能是firedebug的问题,但是在网上查找不到相关内容。折腾了半天发现鼠标展开GET authImg的URL时才会第二次请求验证码,所以明白是因为验证码图片没有缓存造成在firedebug调试窗口查看时需要再次请求的缘故

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值