练习--JSP+Servlet动态生成验证码


ValidateCodeServlet

package com.jsoft;

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.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 {  
  
    /** 
     * Constructor of the object. 
     */  
    public ValidateCodeServlet() {  
        super();  
    }  
  
    /** 
     * Destruction of the servlet. <br> 
     */  
    public void destroy() {  
        super.destroy(); // Just puts "destroy" string in log  
        // Put your code here  
    }  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        response.setContentType("image/jpeg");  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        HttpSession session = request.getSession();  
  
        int width = 60, height = 20;  
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
  
        Graphics g = image.getGraphics();  
  
        Random random = new Random();  
  
        g.setColor(getRandColor(200, 250));  
        g.fillRect(0, 0, width, height);  
  
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));  
  
        g.setColor(getRandColor(160, 200));  
        for (int i = 0; i < 155; i++) {  
            int x = random.nextInt(width);  
            int y = random.nextInt(height);  
            int xl = random.nextInt(12);  
            int yl = random.nextInt(12);  
            g.drawLine(x, y, x + xl, y + yl);  
        }  
  
        String sRand = "";  
        for (int i = 0; i < 4; i++) {  
            String rand = String.valueOf(random.nextInt(10));  
            sRand += rand;  
            g.setColor(new Color(20 + random.nextInt(110), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
            g.drawString(rand, 13 * i + 6, 16);  
        }  
        session.setAttribute("rand", sRand);  
        g.dispose();  
        ServletOutputStream responseOutputStream = response.getOutputStream();  
        ImageIO.write(image, "JPEG", responseOutputStream);  
  
        responseOutputStream.flush();  
        responseOutputStream.close();  
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
  
        doGet(request, response);  
    }  
  
    /** 
     * Initialization of the servlet. <br> 
     * 
     * @throws ServletException if an error occurs 
     */  
    public void init() throws ServletException {  
        // Put your code here  
    }  
    Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色  
        Random random = new Random();  
        if (fc > 255)  
            fc = 255;  
        if (bc > 255)  
            bc = 255;  
        int r = fc + random.nextInt(bc - fc);  
        int g = fc + random.nextInt(bc - fc);  
        int b = fc + random.nextInt(bc - fc);  
        return new Color(r, g, b);  
          
          
    }  
}  
web.xml
 <servlet>  
    <servlet-name>validateCode</servlet-name>  
    <servlet-class>com.jsoft.util.ValidateCodeServlet</servlet-class>  
  </servlet>  
  <servlet-mapping>  
        <servlet-name>validateCode</servlet-name>  
        <url-pattern>/validateCodeServlet</url-pattern>  
  </servlet-mapping>
index.jsp

通过<img>标签中的src属性调用ValidateCodeServlet

<body>
<form action="" method="post">
<table align="center">
  <tr > 
      <td>用户名:</td><td><input type="text" name="name"></td>
  </tr>
  <tr > 
      <td>密码:</td><td><input type="password" name="password"></td>
  </tr>
  <tr> 
      <td>性别:</td>
      <td>
         <input type="radio" name="sex" value="男" checked="checked">男
         <input type="radio" name="sex" value="女">女      
      </td>
  </tr>
  <tr > 
      <td>年龄:</td><td><input type="text" name="age"></td>
  </tr>
  <tr > 
      <td>邮箱:</td><td><input type="text" name="mail"></td>
  </tr>
  <tr > 
      <td>验证码:</td><td><span style="font-size:14px;"><strong><img src="validateCodeServlet"></td></strong></span>
  </tr>
      <td>输入验证码:</td><td><input type="text" name="code"></td>
  </tr>
  <tr> 
      <td colspan="2" align="center">
         <input type="submit" value="注册"> <input type="reset" value="重置"> 
      </td>
  </tr>
  </table>
</form>
</body>
运行效果:


补充另一种写法

package com.jsoft.util;

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.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ValidateCodeServlet extends HttpServlet {
     public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 验证码图片的宽度。
        int width = 60;
        // 验证码图片的高度。
        int height = 20;
        BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics g = buffImg.createGraphics();

        // 创建一个随机数生成器类。
        Random random = new Random();

        // 设定图像背景色(因为是做背景,所以偏淡)
       g.setColor(getRandColor(200, 250));
       g.fillRect(0, 0, width, height);
       // 创建字体,字体的大小应该根据图片的高度来定。
       Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
       // 设置字体。
       g.setFont(font);
        // 画边框。
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
        g.setColor(getRandColor(160,200));
       for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
           int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
       // 设置默认生成4个验证码
      int length = 4;
       // 设置备选验证码:包括"a-z"和数字"0-9"
      String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        int size = base.length();
       // 随机产生4位数字的验证码。
       for (int i = 0; i < length; i++) {
          // 得到随机产生的验证码数字。
           int start = random.nextInt(size);
          String strRand = base.substring(start, start + 1);

           // 用随机产生的颜色将验证码绘制到图像中。
        // 生成随机颜色(因为是做前景,所以偏深)
      //g.setColor(getRandColor(1, 100));
         
       //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
           g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));

            g.drawString(strRand, 15 * i + 6, 24);

           // 将产生的四个随机数组合在一起。
          randomCode.append(strRand);
       }
       // 将四位数字的验证码保存到Session中。
        HttpSession session = request.getSession();
        session.setAttribute("rand", randomCode.toString());

         //图象生效
      g.dispose();
       // 禁止图像缓存。
      response.setHeader("Pragma", "no-cache");
       response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
       response.setContentType("image/jpeg");
       // 将图像输出到Servlet输出流中。
       ServletOutputStream sos = response.getOutputStream();
      ImageIO.write(buffImg, "jpeg", sos);
       sos.flush();
        sos.close();
  }

  Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
      Random random = new Random();
      if (fc > 255)
          fc = 255;
        if (bc > 255)
            bc = 255;
       int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    } 
} 









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值