zoukankan      html  css  js  c++  java
  • 验证码的书写

    package com.hopetesting.web.servlet;

    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;

    /**
    * @author newcityman
    * @date 2019/9/1 - 20:42
    */
    @WebServlet("/checkCode")
    public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 1、创建一个对象,在内存中存放图片(验证码图片对象)
    int width=100;
    int height=50;
    BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    // 2、美化图片
    // 2.1、填充背景色
    Graphics g = image.getGraphics();
    g.setColor(Color.PINK);
    g.fillRect(0,0,width,height);

    // 2.2、画矩形边框
    g.setColor(Color.blue);
    g.drawRect(0,0,width-1,height-1);

    // 2.3、随机生成角标
    String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghighjklmnopqrstuvwxyz0123456789";
    Random ran = new Random();

    // 获取字符
    g.setColor(Color.RED);
    for (int i = 1; i <=4 ; i++) {
    int index = ran.nextInt(str.length());
    char c = str.charAt(index);
    g.drawString(c+"",width/5*i,height/2);
    }
    // 2.4 设置干扰线
    g.setColor(Color.BLACK);

    for(int i=0;i<10;i++){
    int x1 = ran.nextInt(width);
    int x2 = ran.nextInt(width);

    int y1 = ran.nextInt(height);
    int y2 = ran.nextInt(height);
    g.drawLine(x1,y1,x2,y2);
    }


    // 3、将图片输送到页面显示
    ImageIO.write(image,"jpg",response.getOutputStream());


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
    }
    }



    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <script>
    window.onload = function () {
    // 1、获取图片对象
    var img =document.getElementById("checkCode");
    // 2、绑定事件
    img.onclick= function () {
    var date = new Date().getTime();
    img.src="/day15/checkCode?"+date;
    }

    }
    </script>
    </head>
    <body>
    <img src="/day15/checkCode" id="checkCode">
    <a id="change" href="">看不清,换一张</a>
    </body>
    </html>


     
  • 相关阅读:
    【转帖】C#索引器
    .NET Framework升级的挑战
    【我翻译的文章】CodeSmith发布代替和扩展LINQ to SQL的工具——PLINQO
    升级到VS2008后的一些疑惑
    【我翻译的文章】你还需要数据层吗?
    Db4Objects发布Db4o 7.0,支持透明激活
    迎接游戏开发新世界——Zune Game和Micro Game
    20071223成都俱乐部活动
    db4o发布7.2,出现.NET 3.5版本,支持LINQ
    微软推出SCE SDK及其示例MSDN Reader
  • 原文地址:https://www.cnblogs.com/newcityboy/p/11443805.html
Copyright © 2011-2022 走看看