打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Servlet 实现随机验证码

Servlet 实现随机验证码

您的评价:
     
 收藏该经验    
摘要: 网页上的表单经常需要用到验证码,验证码是以图片的形式显示的,图片由后台Servlet生成,通过URI链接显示在网页上。 

首先说明一下随机验证码的流程。


从流程图可以看出,我们需要做一下几步工作。


  1. 通过后台Servlet生成随机图片。
  2. 创建Session会话,并通过登录页面进行验证。
  3. 刷新随机图片超链接后,更换验证码图片。
001/**
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005package net.individuals.web.servlet;
006 
007import java.awt.Color;
008import java.awt.Font;
009import java.awt.Graphics;
010import java.awt.image.BufferedImage;
011import java.io.IOException;
012import java.util.Random;
013import javax.imageio.ImageIO;
014import javax.servlet.ServletException;
015import javax.servlet.annotation.WebServlet;
016import javax.servlet.http.HttpServlet;
017import javax.servlet.http.HttpServletRequest;
018import javax.servlet.http.HttpServletResponse;
019 
020/**
021 *
022 * @author Barudisshu
023 */
024@WebServlet(name = "ImageCodeMakerServlet", urlPatterns = {"/ImageCodeMakerServlet"})
025public class ImageCodeMakerServlet extends HttpServlet {
026 
027    /**
028     * Processes requests for both HTTP
029     * <code>GET</code> and
030     * <code>POST</code> methods.
031     *
032     * @param request servlet request
033     * @param response servlet response
034     * @throws ServletException if a servlet-specific error occurs
035     * @throws IOException if an I/O error occurs
036     */
037    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
038            throws ServletException, IOException {
039        //设置页面不缓存
040        response.setHeader("Pragma""No-cache");
041        response.setHeader("Cache-Control""No-cache");
042        //设置有效期
043        response.setDateHeader("Expires"0);
044 
045        //设置图片的宽度和高度
046        int width = 60, height = 20;
047 
048        //创建一个图像对象
049        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
050 
051        //获取画图对象
052        Graphics g = image.createGraphics();
053 
054        //创建随机对象
055        Random random = new Random();
056 
057        //用随机颜色填充图像背景
058        g.setColor(new Color(255255255));
059 
060        //图像形状
061        g.fillRect(00, width, height);
062 
063        //设置字体
064        g.setFont(new Font("Tahoma", Font.PLAIN, 20));
065 
066        //随机数字符串
067        String sRand = "";
068 
069        for (int i = 0; i < 4; i++) {
070            //生成四个数字字符
071            String rand = String.valueOf(random.nextInt(10));
072            sRand += rand;
073            //生成随机颜色
074            g.setColor(new Color(100 + random.nextInt(155), random.nextInt(100), 100+ random.nextInt(155)));
075            //将随机数字画在图像上
076            g.drawString(rand, (12 + random.nextInt(2)) * i + 618);
077        }
078 
079        //生成干扰线
080        for (int k = 0; k < 24; k++) {
081            g.setColor(getRandomColor(0255));
082            int x = random.nextInt(width);
083            int y = random.nextInt(height);
084            int x1 = random.nextInt(6);
085            int y1 = random.nextInt(6);
086            g.drawLine(x, y, x + x1, y + y1);
087        }
088         
089        //生成干扰像素点
090        for (int i = 0; i < 10; i++) {
091            g.setColor(getRandomColor(50180));
092            int x = random.nextInt(width);
093            int y = random.nextInt(height);
094            g.drawOval(x, y, 11);
095        }
096         
097        //将生成的随机数字写入Session会话
098        request.getSession().setAttribute("randcode", sRand);
099 
100        //使图像生效
101        g.dispose();
102 
103        //输出图像到页面
104        ImageIO.write(image, "JPEG", response.getOutputStream());
105 
106    }
107 
108    /**
109     * 产生一个随机颜色
110     *
111     * @param fc 颜色分量最小值
112     * @param bc 颜色分量最大值
113     * @return
114     */
115    public Color getRandomColor(int fc, int bc) {
116        Random random = new Random();
117        if (fc > 255) {
118            fc = 255;
119        }
120        if (bc > 255) {
121            bc = 255;
122        }
123 
124        int r = fc + random.nextInt(bc - fc);
125        int g = fc + random.nextInt(bc - fc);
126        int b = fc + random.nextInt(bc - fc);
127 
128        return new Color(r, g, b);
129    }
130 
131    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
132    /**
133     * Handles the HTTP
134     * <code>GET</code> method.
135     *
136     * @param request servlet request
137     * @param response servlet response
138     * @throws ServletException if a servlet-specific error occurs
139     * @throws IOException if an I/O error occurs
140     */
141    @Override
142    protected void doGet(HttpServletRequest request, HttpServletResponse response)
143            throws ServletException, IOException {
144        processRequest(request, response);
145    }
146 
147    /**
148     * Handles the HTTP
149     * <code>POST</code> method.
150     *
151     * @param request servlet request
152     * @param response servlet response
153     * @throws ServletException if a servlet-specific error occurs
154     * @throws IOException if an I/O error occurs
155     */
156    @Override
157    protected void doPost(HttpServletRequest request, HttpServletResponse response)
158            throws ServletException, IOException {
159        processRequest(request, response);
160    }
161 
162    /**
163     * Returns a short description of the servlet.
164     *
165     * @return a String containing servlet description
166     */
167    @Override
168    public String getServletInfo() {
169        return "Short description";
170    }// </editor-fold>
171}

实现点击图片更新随机验证码。需要在URL上加上Math.random(),通过不同参数的URL地址响应,否则访问同一个URL资源将不更新。 


1$('#verification').click(function () {
2        $('#verification').attr('src''ImageCodeMakerServlet?' + Math.random());
3    });
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Javaweb 响应——生成验证码
java网络编程-Ajax+servlet实例
使用commons-fileupload例子--孤独的日子
使用XML文件来实现对Servlet的配置
ProdAddServlet
导出文件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服