• javaweb学习总结(九)—— 通过Servlet生成验证码图片


    一、BufferedImage类介绍

    生成验证码图片主要用到了一个BufferedImage类,如下:

    创建一个DrawImage Servlet,用来生成验证码图片

    复制代码
      1 package gacl.response.study;
      2 import java.awt.Color;
      3 import java.awt.Font;
      4 import java.awt.Graphics;
      5 import java.awt.Graphics2D;
      6 import java.awt.image.BufferedImage;
      7 import java.io.IOException;
      8 import java.util.Random;
      9 import javax.imageio.ImageIO;
     10 import javax.servlet.ServletException;
     11 import javax.servlet.http.HttpServlet;
     12 import javax.servlet.http.HttpServletRequest;
     13 import javax.servlet.http.HttpServletResponse;
     14 /**
     15  * 生成随机图片,用来作为验证码
     16  */
     17 public class DrawImage extends HttpServlet {
     18     private static final long serialVersionUID = 3038623696184546092L;
     19     
     20     public static final int WIDTH = 120;//生成的图片的宽度
     21     public static final int HEIGHT = 30;//生成的图片的高度
     22 
     23     public void doGet(HttpServletRequest request, HttpServletResponse response)
     24             throws ServletException, IOException {
     25         this.doPost(request, response);
     26     }
     27 
     28     public void doPost(HttpServletRequest request, HttpServletResponse response)
     29             throws ServletException, IOException {
     30         String createTypeFlag = request.getParameter("createTypeFlag");//接收客户端传递的createTypeFlag标识
     31         //1.在内存中创建一张图片
     32         BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
     33         //2.得到图片
     34         Graphics g = bi.getGraphics();
     35         //3.设置图片的背影色
     36         setBackGround(g);
     37         //4.设置图片的边框
     38         setBorder(g);
     39         //5.在图片上画干扰线
     40         drawRandomLine(g);
     41         //6.写在图片上随机数
     42         //String random = drawRandomNum((Graphics2D) g,"ch");//生成中文验证码图片
     43         //String random = drawRandomNum((Graphics2D) g,"nl");//生成数字和字母组合的验证码图片
     44         //String random = drawRandomNum((Graphics2D) g,"n");//生成纯数字的验证码图片
     45         //String random = drawRandomNum((Graphics2D) g,"l");//生成纯字母的验证码图片
     46         String random = drawRandomNum((Graphics2D) g,createTypeFlag);//根据客户端传递的createTypeFlag标识生成验证码图片
     47         //7.将随机数存在session中
     48         request.getSession().setAttribute("checkcode", random);
     49         //8.设置响应头通知浏览器以图片的形式打开
     50         response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
     51         //9.设置响应头控制浏览器不要缓存
     52         response.setDateHeader("expries", -1);
     53         response.setHeader("Cache-Control", "no-cache");
     54         response.setHeader("Pragma", "no-cache");
     55         //10.将图片写给浏览器
     56         ImageIO.write(bi, "jpg", response.getOutputStream());
     57     }
     58 
     59     /**
     60      * 设置图片的背景色
     61      * @param g
     62      */
     63     private void setBackGround(Graphics g) {
     64         // 设置颜色
     65         g.setColor(Color.WHITE);
     66         // 填充区域
     67         g.fillRect(0, 0, WIDTH, HEIGHT);
     68     }
     69 
     70     /**
     71      * 设置图片的边框
     72      * @param g
     73      */
     74     private void setBorder(Graphics g) {
     75         // 设置边框颜色
     76         g.setColor(Color.BLUE);
     77         // 边框区域
     78         g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
     79     }
     80 
     81     /**
     82      * 在图片上画随机线条
     83      * @param g
     84      */
     85     private void drawRandomLine(Graphics g) {
     86         // 设置颜色
     87         g.setColor(Color.GREEN);
     88         // 设置线条个数并画线
     89         for (int i = 0; i < 5; i++) {
     90             int x1 = new Random().nextInt(WIDTH);
     91             int y1 = new Random().nextInt(HEIGHT);
     92             int x2 = new Random().nextInt(WIDTH);
     93             int y2 = new Random().nextInt(HEIGHT);
     94             g.drawLine(x1, y1, x2, y2);
     95         }
     96     }
     97 
     98     /**
     99      * 画随机字符
    100      * @param g
    101      * @param createTypeFlag
    102      * @return
    103      * String... createTypeFlag是可变参数,
    104      * Java1.5增加了新特性:可变参数:适用于参数个数不确定,类型确定的情况,java把可变参数当做数组处理。注意:可变参数必须位于最后一项
    105      */
    106     private String drawRandomNum(Graphics2D g,String... createTypeFlag) {
    107         // 设置颜色
    108         g.setColor(Color.RED);
    109         // 设置字体
    110         g.setFont(new Font("宋体", Font.BOLD, 20));
    111         //常用的中国汉字
    112         String baseChineseChar = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
    113         //数字和字母的组合
    114         String baseNumLetter = "0123456789ABCDEFGHJKLMNOPQRSTUVWXYZ";
    115         //纯数字
    116         String baseNum = "0123456789";
    117         //纯字母
    118         String baseLetter = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
    119         //createTypeFlag[0]==null表示没有传递参数
    120         if (createTypeFlag.length > 0 && null != createTypeFlag[0]) {
    121             if (createTypeFlag[0].equals("ch")) {
    122                 // 截取汉字
    123                 return createRandomChar(g, baseChineseChar);
    124             }else if (createTypeFlag[0].equals("nl")) {
    125                 // 截取数字和字母的组合
    126                 return createRandomChar(g, baseNumLetter);
    127             }else if (createTypeFlag[0].equals("n")) {
    128                 // 截取数字
    129                 return createRandomChar(g, baseNum);
    130             }else if (createTypeFlag[0].equals("l")) {
    131                 // 截取字母
    132                 return createRandomChar(g, baseLetter);
    133             }
    134         }else {
    135             // 默认截取数字和字母的组合
    136             return createRandomChar(g, baseNumLetter);
    137         }
    138         
    139         return "";
    140     }
    141 
    142     /**
    143      * 创建随机字符
    144      * @param g
    145      * @param baseChar
    146      * @return 随机字符
    147      */
    148     private String createRandomChar(Graphics2D g,String baseChar) {
    149         StringBuffer sb = new StringBuffer();
    150         int x = 5;
    151         String ch ="";
    152         // 控制字数
    153         for (int i = 0; i < 4; i++) {
    154             // 设置字体旋转角度
    155             int degree = new Random().nextInt() % 30;
    156             ch = baseChar.charAt(new Random().nextInt(baseChar.length())) + "";
    157             sb.append(ch);
    158             // 正向角度
    159             g.rotate(degree * Math.PI / 180, x, 20);
    160             g.drawString(ch, x, 20);
    161             // 反向角度
    162             g.rotate(-degree * Math.PI / 180, x, 20);
    163             x += 30;
    164         }
    165         return sb.toString();
    166     }
    167 }
    复制代码

    运行结果如下:

      

    二、在Form表单中使用验证码图片

    复制代码
     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     3 <html>
     4   <head>
     5     <title>在Form表单中使用验证码</title>
     6     <script type="text/javascript">
     7     //刷新验证码
     8     function changeImg(){
     9         document.getElementById("validateCodeImg").src="${pageContext.request.contextPath}/servlet/DrawImage?"+Math.random();
    10     }
    11     </script>
    12   </head>
    13   
    14   <body>
    15         <form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
    16             验证码:<input type="text" name="validateCode"/>
    17             <img alt="验证码看不清,换一张" src="${pageContext.request.contextPath}/servlet/DrawImage" id="validateCodeImg" onclick="changeImg()">
    18             <a href="javascript:void(0)" onclick="changeImg()">看不清,换一张</a>
    19             <br/>
    20             <input type="submit" value="提交">
    21         </form>
    22   </body>
    23 </html>
    复制代码

    运行结果:

      

      DrawImage Servlet除了可以生成的字母和数字的组合的验证码图片之外,还可以生成汉字,纯数字,纯字母的验证码图片,只需要向DrawImage Servlet传递约定好的生成标识符参数即可,如下所示:

    复制代码
     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     3 <html>
     4   <head>
     5     <title>在Form表单中使用验证码</title>
     6     <script type="text/javascript">
     7     //刷新验证码
     8     function changeImg(obj,createTypeFlag){
     9         document.getElementById(obj.id).src="${pageContext.request.contextPath}/servlet/DrawImage?createTypeFlag="+createTypeFlag+"&"+Math.random();
    10     }
    11     </script>
    12   </head>
    13   
    14   <body>
    15         <form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
    16             数字字母混合验证码:<input type="text" name="validateCode"/>
    17             <img alt="验证码看不清,换一张" src="${pageContext.request.contextPath}/servlet/DrawImage" id="validateCodeImg1" onclick="changeImg(this,'nl')">
    18             <br/>
    19             中文验证码:<input type="text" name="validateCode"/>
    20             <img alt="验证码看不清,换一张" src="${pageContext.request.contextPath}/servlet/DrawImage?createTypeFlag=ch" id="validateCodeImg2" onclick="changeImg(this,'ch')">
    21             <br/>
    22             英文验证码:<input type="text" name="validateCode"/>
    23             <img alt="验证码看不清,换一张" src="${pageContext.request.contextPath}/servlet/DrawImage?createTypeFlag=l" id="validateCodeImg3" onclick="changeImg(this,'l')">
    24             <br/>
    25             数字验证码:<input type="text" name="validateCode"/>
    26             <img alt="验证码看不清,换一张" src="${pageContext.request.contextPath}/servlet/DrawImage?createTypeFlag=n" id="validateCodeImg4" onclick="changeImg(this,'n')">
    27             <br/>
    28             <input type="submit" value="提交">
    29         </form>
    30   </body>
    31 </html>
    复制代码

    运行结果如下:

      

    三、服务器端对form表单提交上来的验证码处理

    复制代码
     1 package gacl.response.study;
     2 import java.io.IOException;
     3 import javax.servlet.ServletException;
     4 import javax.servlet.http.HttpServlet;
     5 import javax.servlet.http.HttpServletRequest;
     6 import javax.servlet.http.HttpServletResponse;
     7 /**
     8  * @author gacl
     9  * 服务器端接收到验证码后的处理
    10  */
    11 public class CheckServlet extends HttpServlet {
    12     public void doGet(HttpServletRequest request, HttpServletResponse response)
    13             throws ServletException, IOException {
    14         String clientCheckcode = request.getParameter("validateCode");//接收客户端浏览器提交上来的验证码
    15         String serverCheckcode = (String) request.getSession().getAttribute("checkcode");//从服务器端的session中取出验证码
    16         if (clientCheckcode.equals(serverCheckcode)) {//将客户端验证码和服务器端验证比较,如果相等,则表示验证通过
    17             System.out.println("验证码验证通过!");
    18         }else {
    19             System.out.println("验证码验证失败!");
    20         }
    21     }
    22 
    23     public void doPost(HttpServletRequest request, HttpServletResponse response)
    24             throws ServletException, IOException {
    25         doGet(request, response);
    26     }
    27 
    28 }
    复制代码
  • 相关阅读:
    查看mysql数据库容量大小
    通过shell监控网页是否正常,然后促发邮件告警
    Linux shell标准输入,标准输出,错误输出
    linux资源管理命令之-----vmstat
    linux基础命令--lsof
    squid之------ACL控制
    JDK的二进制安装
    重置grafana密码
    CentOS 7添加开机启动服务脚本
    LVM逻辑卷理论及配置
  • 原文地址:https://www.cnblogs.com/telwanggs/p/5336274.html
Copyright © 2020-2023  润新知