动态验证码_动态验证码软件 - CSDN
  • Web动态生成验证码

    2020-07-30 23:32:03
    用JSP和Servlet写的用于动态生成验证码,点击可刷新。
  • 动态生成验证码

    2020-04-06 21:11:13
    要求:点一次图片,换一次验证码 分析:点一次图片,触发onclick事件,利用function函数设置新的src属性,加时间戳 <script type="text/javascript"> function refreshCode(){ //1.获取验证码图片对象 var...

    要求:
    1、点一次图片,换一次验证码
    2、校验用户输入的验证码 和 随机生成的验证码是否一致(在LoginServlet里面校验)

    分析:
    1、点一次图片,触发onclick事件,利用function函数设置新的src属性,加时间戳

     <script type="text/javascript">
            function refreshCode(){
                //1.获取验证码图片对象
                var vcode = document.getElementById("vcode");
    
                //2.设置其src属性,加时间戳
                vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
            }
        </script>
    

    2、验证码的校验

    //获取用户填写验证码
    String verifycode = request.getParameter("verifycode");
    
    //获取随机生成的验证码进行校验
    HttpSession session = request.getSession();
    String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
    session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
    
    //验证码不正确
    if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //提示错误信息
            request.setAttribute("login_msg","验证码错误!");
            //使用request转发 跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
    		return;
    }
    

    实例:

    首先给出 CheckCodeServlet.java,可以当作工具类使用

    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    
    @WebServlet("/checkCodeServlet")
    public class CheckCodeServlet extends HttpServlet {
    	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    		
    		//服务器通知浏览器不要缓存
    		response.setHeader("pragma","no-cache");
    		response.setHeader("cache-control","no-cache");
    		response.setHeader("expires","0");
    		
    		//在内存中创建一个长80,宽30的图片,默认黑色背景
    		//参数一:长
    		//参数二:宽
    		//参数三:颜色
    		int width = 80;
    		int height = 30;
    		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    		
    		//获取画笔
    		Graphics g = image.getGraphics();
    		//设置画笔颜色为灰色
    		g.setColor(Color.GRAY);
    		//填充图片
    		g.fillRect(0,0, width,height);
    		
    		//产生4个随机验证码,12Ey
    		String checkCode = getCheckCode();
    		//将验证码放入HttpSession中
    		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
    		
    		//设置画笔颜色为黄色
    		g.setColor(Color.YELLOW);
    		//设置字体的小大
    		g.setFont(new Font("黑体",Font.BOLD,24));
    		//向图片上写入验证码
    		g.drawString(checkCode,15,25);
    		
    		//将内存中的图片输出到浏览器
    		//参数一:图片对象
    		//参数二:图片的格式,如PNG,JPG,GIF
    		//参数三:图片输出到哪里去
    		ImageIO.write(image,"PNG",response.getOutputStream());
    	}
    	/**
    	 * 产生4位随机字符串 
    	 */
    	private String getCheckCode() {
    		String base = "0123456789ABCDEFGabcdefg";
    		int size = base.length();
    		Random r = new Random();
    		StringBuffer sb = new StringBuffer();
    		for(int i=1;i<=4;i++){
    			//产生0到size-1的随机值
    			int index = r.nextInt(size);
    			//在base字符串中获取下标为index的字符
    			char c = base.charAt(index);
    			//将c放入到StringBuffer中去
    			sb.append(c);
    		}
    		return sb.toString();
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		this.doGet(request,response);
    	}
    }
    

    给出login.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <html lang="zh-CN">
      <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>管理员登录</title>
    
        <!-- 1. 导入CSS的全局样式 -->
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
        <script src="js/jquery-2.1.0.min.js"></script>
        <!-- 3. 导入bootstrap的js文件 -->
        <script src="js/bootstrap.min.js"></script>
        <script type="text/javascript">
        </script>
        
        <script type="text/javascript">
            //切换验证码
            function refreshCode(){
                //1.获取验证码图片对象
                var vcode = document.getElementById("vcode");
    
                //2.设置其src属性,加时间戳
                vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
            }
        </script>
        
      </head>
      <body>
      	<div class="container" style="width: 400px;">
      		<h3 style="text-align: center;">管理员登录</h3>
            <form action="${pageContext.request.contextPath}/loginServlet" method="post">
    	      <div class="form-group">
    	        <label for="user">用户名:</label>
    	        <input type="text" name="user" class="form-control" id="user" placeholder="请输入用户名"/>
    	      </div>
    	      
    	      <div class="form-group">
    	        <label for="password">密码:</label>
    	        <input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
    	      </div>
    	      
    	      <div class="form-inline">
    	        <label for="vcode">验证码:</label>
    	        <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
    	        <a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a>
    	      </div>
    	      <hr/>
    	      <div class="form-group" style="text-align: center;">
    	        <input class="btn btn btn-primary" type="submit" value="登录">
    	       </div>
    	  	</form>
    		
    		<!-- 出错显示的信息框 -->
    	  	<div class="alert alert-warning alert-dismissible" role="alert">
    		  <button type="button" class="close" data-dismiss="alert" >
    		  	<span>&times;</span></button>
    		   <strong>登录失败!</strong>
    		</div>
      	</div>
      </body>
    </html>
    

    在这里插入图片描述
    在这里插入图片描述

    展开全文
  • Java动态验证码

    千次阅读 2018-04-27 17:53:12
    一、效果图二、后面是使用SpringBoot。https://download.csdn.net/download/qq_36135928/10379447... //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 public...

    一、效果图


    二、后面是使用SpringBoot。

    https://download.csdn.net/download/qq_36135928/10379447点击打开链接

    三、核心代码

    public class VerificationImageUtils {
        //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
        public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        private static Random random = new Random();
    
        /**
         * 使用系统默认字符源生成验证码
         * @param verifySize    验证码长度
         * @return
         */
        public static String generateVerifyCode(int verifySize){
            return generateVerifyCode(verifySize, VERIFY_CODES);
        }
        /**
         * 使用指定源生成验证码
         * @param verifySize    验证码长度
         * @param sources   验证码字符源
         * @return
         */
        public static String generateVerifyCode(int verifySize, String sources){
            if(sources == null || sources.length() == 0){
                sources = VERIFY_CODES;
            }
            int codesLen = sources.length();
            Random rand = new Random(System.currentTimeMillis());
            StringBuilder verifyCode = new StringBuilder(verifySize);
            for(int i = 0; i < verifySize; i++){
                verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
            }
            return verifyCode.toString();
        }
    
        /**
         * 生成随机验证码文件,并返回验证码值
         * @param w
         * @param h
         * @param outputFile
         * @param verifySize
         * @return
         * @throws IOException
         */
        public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
            String verifyCode = generateVerifyCode(verifySize);
            outputImage(w, h, outputFile, verifyCode);
            return verifyCode;
        }
    
        /**
         * 输出随机验证码图片流,并返回验证码值
         * @param w
         * @param h
         * @param os
         * @param verifySize
         * @return
         * @throws IOException
         */
        public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
            String verifyCode = generateVerifyCode(verifySize);
            outputImage(w, h, os, verifyCode);
            return verifyCode;
        }
    
        /**
         * 生成指定验证码图像文件
         * @param w
         * @param h
         * @param outputFile
         * @param code
         * @throws IOException
         */
        public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
            if(outputFile == null){
                return;
            }
            File dir = outputFile.getParentFile();
            if(!dir.exists()){
                dir.mkdirs();
            }
            try{
                outputFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(outputFile);
                outputImage(w, h, fos, code);
                fos.close();
            } catch(IOException e){
                throw e;
            }
        }
    
        /**
         * 输出指定验证码图片流
         * @param w
         * @param h
         * @param os
         * @param code
         * @throws IOException
         */
        public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
            int verifySize = code.length();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Random rand = new Random();
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            Color[] colors = new Color[5];
            Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                    Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                    Color.PINK, Color.YELLOW };
            float[] fractions = new float[colors.length];
            for(int i = 0; i < colors.length; i++){
                colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
                fractions[i] = rand.nextFloat();
            }
            Arrays.sort(fractions);
    
            g2.setColor(Color.GRAY);// 设置边框色
            g2.fillRect(0, 0, w, h);
    
            Color c = getRandColor(200, 250);
            g2.setColor(c);// 设置背景色
            g2.fillRect(0, 2, w, h-4);
    
            //绘制干扰线
            Random random = new Random();
            g2.setColor(getRandColor(160, 200));// 设置线条的颜色
            for (int i = 0; i < 20; i++) {
                int x = random.nextInt(w - 1);
                int y = random.nextInt(h - 1);
                int xl = random.nextInt(6) + 1;
                int yl = random.nextInt(12) + 1;
                g2.drawLine(x, y, x + xl + 40, y + yl + 20);
            }
    
            // 添加噪点
            float yawpRate = 0.05f;// 噪声率
            int area = (int) (yawpRate * w * h);
            for (int i = 0; i < area; i++) {
                int x = random.nextInt(w);
                int y = random.nextInt(h);
                int rgb = getRandomIntColor();
                image.setRGB(x, y, rgb);
            }
    
            shear(g2, w, h, c);// 使图片扭曲
    
            g2.setColor(getRandColor(100, 160));
            int fontSize = h-4;
            Font font = new Font("Algerian", Font.ITALIC, fontSize);
            g2.setFont(font);
            char[] chars = code.toCharArray();
            for(int i = 0; i < verifySize; i++){
                AffineTransform affine = new AffineTransform();
                affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
                g2.setTransform(affine);
                g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
            }
    
            g2.dispose();
            ImageIO.write(image, "jpg", os);
        }
    
        private static Color getRandColor(int fc, int bc) {
            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);
        }
    
        private static int getRandomIntColor() {
            int[] rgb = getRandomRgb();
            int color = 0;
            for (int c : rgb) {
                color = color << 8;
                color = color | c;
            }
            return color;
        }
    
        private static int[] getRandomRgb() {
            int[] rgb = new int[3];
            for (int i = 0; i < 3; i++) {
                rgb[i] = random.nextInt(255);
            }
            return rgb;
        }
    
        private static void shear(Graphics g, int w1, int h1, Color color) {
            shearX(g, w1, h1, color);
            shearY(g, w1, h1, color);
        }
    
        private static void shearX(Graphics g, int w1, int h1, Color color) {
    
            int period = random.nextInt(2);
    
            boolean borderGap = true;
            int frames = 1;
            int phase = random.nextInt(2);
    
            for (int i = 0; i < h1; i++) {
                double d = (double) (period >> 1)
                        * Math.sin((double) i / (double) period
                        + (6.2831853071795862D * (double) phase)
                        / (double) frames);
                g.copyArea(0, i, w1, 1, (int) d, 0);
                if (borderGap) {
                    g.setColor(color);
                    g.drawLine((int) d, i, 0, i);
                    g.drawLine((int) d + w1, i, w1, i);
                }
            }
    
        }
    
        private static void shearY(Graphics g, int w1, int h1, Color color) {
    
            int period = random.nextInt(40) + 10; // 50;
    
            boolean borderGap = true;
            int frames = 20;
            int phase = 7;
            for (int i = 0; i < w1; i++) {
                double d = (double) (period >> 1)
                        * Math.sin((double) i / (double) period
                        + (6.2831853071795862D * (double) phase)
                        / (double) frames);
                g.copyArea(i, 0, 1, h1, 0, (int) d);
                if (borderGap) {
                    g.setColor(color);
                    g.drawLine(i, (int) d, i, 0);
                    g.drawLine(i, (int) d + h1, i, h1);
                }
    
            }
    
        }
    //    public static void main(String[] args) throws IOException{
    //        File dir = new File("F:/verifies");
    //        int w = 200, h = 80;
    //        for(int i = 0; i < 50; i++){
    //            String verifyCode = generateVerifyCode(4);
    //            File file = new File(dir, verifyCode + ".jpg");
    //            outputImage(w, h, file, verifyCode);
    //        }
    //    }
    }


    @RestController
    @RequestMapping("/captchaImage")
    public class CaptchaImageController {
    
    	/**
    	 * 生成验证码
    	 *
    	 * @param request
    	 * @param response
    	 * @param model
    	 * @throws ServletException
    	 * @throws IOException
    	 */
    	@RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    	public void ImageCaptcha(HttpServletRequest request, HttpServletResponse response, Model model)
    			throws ServletException, IOException {
    
    		try {
    			// get the session id that will identify the generated captcha.
    			// the same id must be used to validate the response, the session id
    			// is a good candidate!
    			response.setHeader("Cache-Control", "no-store");
    			response.setHeader("Pragma", "no-cache");
    			response.setDateHeader("Expires", 0);
    			response.setContentType("image/jpeg");
    
    			String verifyCode = VerificationImageUtils.generateVerifyCode(4);
    			//存入会话session
    			HttpSession session = request.getSession(true);
    			session.setAttribute("verificationImage", verifyCode.toLowerCase());
    			//生成图片
    			int w = 200, h = 80;
    			VerificationImageUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    
    		} catch (IllegalArgumentException e) {
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }

    html

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    		<meta charset="utf-8">
    		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    		<meta name="renderer" content="webkit"/>
    		<meta name="format-detection" content="telephone=no,email=no"/>
    		<title>验证码</title>
    		<link rel="stylesheet" href="/css/login.css"/>
    	</head>
    	<body>
    		<div class="yzm">
    			<input type="text" name="" id="verifyCode" value=""  placeholder="请输入验证码"/>
    			<img id="kaptcha" onClick="javascript:changeKaptcha();"
    				 src="/captchaImage/kaptcha"/>
    		</div>
    	</body>
    </html>
    <script src="/js/jquery.js"></script>
    <script type="text/javascript">
        function changeKaptcha(){
            $("#kaptcha").attr("src","/captchaImage/kaptcha?" + Math.floor(Math.random() * 100));
            $("#verify").select();
        }
    </script>





    展开全文
  • 动态生成验证码!利用读取文件流来生成验证码!简洁实用!
  • 动态验证码源码(详解)

    千次阅读 2014-03-27 13:59:04
    public partial class Admin_RandomImage : System.Web.UI.Page {  protected void Page_Load(object sender, EventArgs e)  {  if (!IsPostBack)  {  CreateCheckCode(GetChe

    public partial class Admin_RandomImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CreateCheckCode(GetCheckCode());
            }
        }

        //生成随机数
        /// <summary>
        /// 生成随机验证码字符串
        /// </summary>
        /// <returns>生成的随机验证码字符串</returns>
        private string GetCheckCode()
        {
            int number;
            string code = string.Empty;//随机值种子
            Random rd = new Random();
            for (int i = 0; i < 4; i++)//验证码长度是4
            {
                number = rd.Next();
                number = number % 36;
                if (number < 10)
                {
                    number += 48;
                }
                else
                {
                    number += 55;
                }
                code += ((char)number).ToString();
            }
            Session["CheckCode"] = code;//在session中保存验证码
            return code;
        }

        //画出验证码
        /// <summary>
        /// 根据验证码输出图片
        /// </summary>
        /// <param name="ccode">生成的随机验证码</param>
        private void CreateCheckCode(string ccode)
        {
            //若验证码为空,则直接返回
            if (ccode == null || ccode.Trim() == string.Empty)
            {
                return;
            }
            //根据验证码长度确定输出图片的长度
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(65, 30);
            //创建Graphics对象
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机数种子
                Random rd = new Random();
                //清空图片背景颜色
                g.Clear(Color.White);
                //画图片的背景噪音线10条
                //--------------------------------------------------------------------------
                for (int i = 0; i < 10; i++)
                {
                    //噪音线起点坐标(x1,y1),终点坐标(x2,y2)
                    int x1 = rd.Next(image.Width);
                    int x2 = rd.Next(image.Width);
                    int y1 = rd.Next(image.Height);
                    int y2 = rd.Next(image.Height);
                    //用蓝色画出噪音线
                    Pen p = new Pen(Color.Blue);
                    g.DrawLine(p, x1, y1, x2, y2);
                }

                //Brush b=Brushes.Silver;
                //g.FillRectangle(b,0,0,image.Width,image.Height);

     

                //验证码字体:15号Arial,粗斜体,下划线
                Font f = new Font("Arial", 15, (FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline));

                //线性渐变画刷
                LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Purple, 1.2f, true);
                g.DrawString(ccode, f, lgb, 2, 2);

                //画图片的前噪音点100个
                for (int i = 0; i < 100; i++)
                {
                    int x = rd.Next(image.Width);
                    int y = rd.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(rd.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Purple), 0, 0, image.Width - 1, image.Height - 1);

                //创建内存流用于输出图片

                using (MemoryStream ms = new MemoryStream())
                {
                    //图片类型指定为PNG
                    image.Save(ms, ImageFormat.Png);
                    //清除缓冲区中的所有输出
                    Response.ClearContent();
                    //输出流HTTP MIME类型设置为:image/PNG
                    Response.ContentType = "image/png";
                    //输出图片的二进制流
                    Response.BinaryWrite(ms.ToArray());
                }
            }
            finally
            {
                //释放Bitmap对象和Graphics对象
                g.Dispose();
                image.Dispose();
            }
        }


    }

    展开全文
  • 登陆界面如何生成动态验证码

    千次阅读 2018-04-13 14:25:25
    在设计登录界面时验证码是必不可少,本实例将简单的生成动态验证码。 根据个人需求将生成验证码代码放到不同的的地方,可以放到前段控制器中通过请求方式生成验证码,也可已将代码放到一个JSP页面通过应用JSP页面...

    在设计登录界面时验证码是必不可少,本实例将简单的生成动态验证码。
    根据个人需求将生成验证码代码放到不同的的地方,可以放到前段控制器中通过请求方式生成验证码,也可已将代码放到一个JSP页面通过应用JSP页面生成验证码
    工具:J2EE

    通过jsp生成验证码

    源代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@page import="java.awt.image.BufferedImage"%>  
    <%@page import="java.awt.Graphics2D"%>  
    <%@page import="java.awt.Color"%>  
    <%@page import="java.awt.Font"%>  
    <%@page import="javax.imageio.ImageIO"%>  
    <%@page import="java.util.Random"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>验证码</title>
    </head>
    <body>
    <%  
        int width = 60;//定义图片的宽度  
        int height = 20;//定义图片的高度  
        // 创建具有可访问图像数据缓冲区的Image  
        BufferedImage buffImg = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = buffImg.createGraphics();  
    
        // 创建一个随机数生成器  
        Random random = new Random();  
        //将图像填充为 白色  
        g.setColor(Color.WHITE);  
        g.fillRect(0, 0, width, height);  
    
        // 创建字体,字体的大小应该根据图片的高度来定  
        Font font = new Font("Times New Roman", Font.PLAIN, 18);  
        // 设置字体  
        g.setFont(font);  
    
        // 画边框  
        g.setColor(Color.BLACK);  
        g.drawRect(0, 0, width - 1, height - 1);  
    
        // 随机产生160条干扰线 ,使图像中的验证码不易被其它程序探测到
        g.setColor(Color.LIGHT_GRAY);  
        for (int i = 0; i < 160; i++) {  
            int x = random.nextInt(width);  
            int y = random.nextInt(height);  
            int x1 = random.nextInt(12);  
            int y1 = random.nextInt(12);  
            g.drawLine(x, y, x + x1, y + y1);  
        }  
    
        // randomCode 用于保存随机产生的验证码  ,以便用户登陆后进行验证
        StringBuffer randomCode = new StringBuffer();  
        int red = 0, green = 0, blue = 0;  
    
        // 随机产生4位数字的验证码  
        for (int i = 0; i < 4; i++) {  
            // 得到随机产生的验证码数字  
            String strRand = String.valueOf(random.nextInt(10));  
    
            // 产生随机的颜色分量来构造颜色值 ,这样输出的每位数字的颜色值都将不同 
            red = random.nextInt(110);  
            green = random.nextInt(50);  
            blue = random.nextInt(50);  
    
            // 用随机产生的颜色将验证码绘制到图像中  
            g.setColor(new Color(red, green, blue));  
            g.drawString(strRand, 13 * i + 6, 16);  
            //将产生的四个随机数组合在一起
            randomCode.append(strRand);  
        }  
    
        // 将四位数字的验证码保存到session中  
        //HttpSession session = request.getSession();  
        session.setAttribute("randomCode", randomCode.toString());  
    
        // 禁止图像缓存  
        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.close();  
        //sos = null;  
        out.clear();  
        out = pageContext.pushBody();  
    %>  
    </body>
    </html>

    运行结果:
    这里写图片描述

    在登录界面显示验证码

    1.登录界面
    源代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录界面</title>
    <script src="./js/jquery-1.9.0.min.js"></script>  
    <script type="text/javascript">  
    $(function(){  
        $("#loginform_submit").click(function(){  
            if(checkInput()){  
    
               $("#form1").submit();  
            }else{  
                return false;  
            }  
        }  
        );  
    });  
    
    function checkInput(){  
        var flag = true;  
        //判断用户名  
        if($("input[name=username]").val()==null || $("input[name=username]").val()==""){  
            alert("用户名不能等于空");  
            $("input[name=username]").focus();  
            flag =false;  
            return ;  
        }  
        //判断密码  
        if($("input[name=password]").val()==null || $("input[name=password]").val()==""){  
            alert("密码不能等于空");  
            $("input[name=password]").focus();  
            flag =false;  
            return ;  
        }  
        //判断验证码  
        if($("#validationCode").val()==null || $("#validationCode").val()==""){  
            alert("验证码不能为空");  
            $("#validationCode").focus();  
            flag =false;  
            return ;  
        }  
        return flag;  
    }
    
    
    
    </script>
    
    </head>
    <body>
    <div id="loginpanelwrap" align="center">  
            <div>  
                <div>登录</div>  
            </div>  
    
            <form id="form1" action="do_login.jsp" method="post">  
                       <table>
                       <tr>  
                       <td> <label>用户名:</label>  
                        <input id="username" type="text" name="username" /><br>  
    
                       </td>  
                       </tr>
                       </table>  
                    <label>密码:</label>  
                    <input type="password" name="password" id="password"/><br>  
    
                    <label>验证码:</label>  
                    <input type="text" name="validationCode" id="validationCode"/>  
                    <!--<img id="validationCode_img"  src="validate.jsp"><br>-->
                    <img src="validate.jsp"  id="picture" onClick="change()" id="picture"><!--点击验证码可以进行动态刷新  -->
                    <!--刷新验证码的src-->
                    <script>  
                  function change(){  
                  var pic=document.getElementById("picture");  
                  var i=Math.random();//目的是使页面不一样  
                  pic.src="validate.jsp?id="+i;  
                     }  
                     </script>    
                    <table>      
                     <tr> 
                   <input type="submit" id="loginform_submit" value="登录"/>               
                    </tr>  
                </table>
    
            </form>  
    
        </div>  
    </body>
    </html>

    运行结果如下:
    这里写图片描述

    展开全文
  • Web页面动态验证码

    千次阅读 2018-02-08 18:51:42
    结果如下: ...动态验证码实现首先得有一个算法。 定义一个数组用来存放生成的验证码 String ver[] = new String[62]; 第一种,定义一个字符串数组,由0-9,a-z,A-Z组成,共62 public void in...
  • 2019独角兽企业重金招聘Python工程师标准>>> ...
  • .NET MVC Gif动态验证码,模仿苹果商店验证码, .NET MVC 动态验证码
  • vue实现动态验证码和短信验证码

    千次阅读 2018-05-28 15:28:02
    一:动态验证码:html部分&lt;div style="display: flex;align-items: center;"&gt; &lt;span&gt;验证码:&lt;/span&gt; &lt;i-input v-model="picLyanzhengma" ...
  • 最近在做的一个项目中遇到了输入动态验证码的问题,起初在网上也搜到一些代码,但是感觉都不是想要的那种,在web开发中,动态验证码需要显示在jsp页面中,然后在输入框中写入显示的东西,判断正确与否。这里只是做...
  • Qt – 获取12306动态验证码图片 本文转载自:http://beself.top/2018/09/16/qt-get_12306verificationcode/ 背景 经常出行的人就知道买火车票是一件比较困难的事情,特别是节假日,抢票就更加艰难了,抢票的...
  • 用java实现动态验证码的效果,源代码可以直接拷贝到项目中用
  • 如何用代码实现手机接收动态验证码 我们现在注册一个app应用经常会使用手机验证码,那Java程序怎么实现的呢?首先我们要明白,手机接收验证码是基于三大运营商的服务实现的,而阿里云服务为我们实现了免去和运营商直接...
  • ●登录名和密码是同时验证的,并不是先验证登录...现在web工程多是这么进行登录用户名和密码的验证●动态验证码是采用Image的一个servlert实时生成动态验证码,并且servlert将生成的动态验证码保存在session中,在j...
  • php生成动态验证码

    2019-08-30 10:49:28
    代码部分 <?.../** * Created by PhpStorm. * User: QLX * Date: 2019/8/29 ... * 生成动态验证码 */ header('Content-Type:image/jpeg'); $width = 120; $height = 40; $chars = array('a','b...
  • Google Authenticator配置SSH登录动态验证码 需求说明: 1、一般ssh登录服务器,只需要输入账号和密码。 2、本教程的目的:在账号和密码之间再增加一个验证码,只有输入正确的验证码之,再输入密码才能登录。这样...
  • 在服务端实现简单的动态验证码 不废话,直接见代码 1、首先:CheckCodeServlet.java ,实现动态画图功能 import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet....
  • 登录页面动态验证码的设置 采用php中创建对象的思想进行动态验证码的设置 1、创建出一个背景图片,用来存放动态码输出位置 1 function createImage(){ 2 // 创建图片对象,并设置图片的宽高 ...
  • Web生成动态验证码
1 2 3 4 5 ... 20
收藏数 25,647
精华内容 10,258
关键字:

动态验证码