• javaweb项目中表单生成的验证码以及校验


    首先先来看一下项目的结构吧,有两个servlet,一个是进行验证码的生成以及存储的,一个是进行校验的,还有一个jsp页面是用来实现form表单的书写和展示:

    我们只需要看这三个就行了,其他的自动忽略;记得写完以后要配置一下web.xml里面的路径,不然访问不到servlet里面的内容。

    说一下思路:我们使用BufferedImage把绘制出来的传递到前台,然后把生成的随即数字存到session里面,然后再在表单验证的java当中提取session里面的数值进行比较:

    绘制验证码的servlet:

    package Response;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    
    import java.util.Random;
    
    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 javax.imageio.ImageIO;
    
    import java.io.IOException;
    
    
    @WebServlet(name = "Response03", urlPatterns = {"/Response/Response03"})
    public class Response03 extends HttpServlet {
        public static final long serialVersionUID = 3038623696184546092L;
        public static final int WIDTH = 120; //生成图片的宽度
        public static final int HEIGHT = 30;//生成图片的长度
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setHeader("refresh", "2"); //设置响应头控制浏览器每隔3S刷新页面
            String createTypeFlag = request.getParameter("createTypeFlag");//向客户端传递的createTypeFlag标识
            //1.在内存中创建一张图片
            BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            //2.得到图片
            Graphics g = bi.getGraphics();
            //3.设置图片的背景色
            setBackGround(g);
            //4.设置图片的边框
            setBorder(g);
            //5.在图片上画干扰线
            int num = 5;//控制线条的数量
            drawRandomLine(g, num);
            //6.写在图片上的随机数
            int num2 = 4;//最多4个,这个地方可以通过调节输入框的宽度来进行调节
            //String random = drawRandomNum((Graphics2D) g,"ch");//生成中文验证码图片
            //String random = drawRandomNum((Graphics2D) g,"nl");//生成数字和字母组合的验证码图片
            //String random = drawRandomNum((Graphics2D) g,"n");//生成纯数字的验证码图片
            //String random = drawRandomNum((Graphics2D) g,"l");//生成纯字母的验证码图片
            String random = drawRandomNum((Graphics2D) g, num2, createTypeFlag);
            //7.将随机数写在session里面
            request.getSession().setAttribute("checkcode", random);
            //8.设置响应头通知浏览器以图片的方式打开
            response.setContentType("image/jpeg");
            //9.设置响应头控制浏览器不要缓存
            response.setDateHeader("expries", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            //10.、把图片写进浏览器
            ImageIO.write(bi, "jpg", response.getOutputStream());
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
    
        }
    
    
        /****设置图片的背景色***/
        private void setBackGround(Graphics g) {
            //设置颜色
            g.setColor(Color.WHITE);
            //填充区域
            g.fillRect(0, 0, WIDTH, HEIGHT);
        }
    
        /***设置图片的边框**/
        private void setBorder(Graphics g) {
            g.setColor(Color.BLUE);
            g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
        }
    
        /*****设置图片的随即线条******/
        private void drawRandomLine(Graphics g, int num) {
            g.setColor(Color.GREEN);
            //设置线条个数并划线
            for (int i = 0; i < num; i++) {
                int x1 = new Random().nextInt(WIDTH);
                int y1 = new Random().nextInt(HEIGHT);
                int x2 = new Random().nextInt(WIDTH);
                int y2 = new Random().nextInt(HEIGHT);
                g.drawLine(x1, y1, x2, y2);
            }
        }
    
        /*******画随机字符*******/
        private String drawRandomNum(Graphics2D g, int num, String...createTypeFlag) {
            g.setColor(Color.RED);
            g.setFont(new Font("宋体", Font.BOLD, 20));
            //常用的中国汉字
            String baseChineseChar = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
            //数字和字母的组合
            String baseNumLetter = "0123456789ABCDEFGHJKLMNOPQRSTUVWXYZ";
            //纯数字
            String baseNum = "0123456789";
            //纯字母
            String baseLetter = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
            if (createTypeFlag.length > 0 && null != createTypeFlag[0]) {
                if (createTypeFlag[0].equals("ch")) {
                    // 截取汉字
                    return createRandomChar(g, baseChineseChar, num);
                } else if (createTypeFlag[0].equals("nl")) {
                    // 截取数字和字母的组合
                    return createRandomChar(g, baseNumLetter, num);
                } else if (createTypeFlag[0].equals("n")) {
                    // 截取数字
                    return createRandomChar(g, baseNum, num);
                } else if (createTypeFlag[0].equals("l")) {
                    // 截取字母
                    return createRandomChar(g, baseLetter, num);
                }
            } else {
                // 默认截取数字和字母的组合
                return createRandomChar(g, baseNumLetter,num);
            }
    
            return "";
        }
    
        /**
         * 创建随机字符
         **/
        private String createRandomChar(Graphics2D g, String baseChar, int num) {
            StringBuffer sb = new StringBuffer();
            int x = 5;
            String ch = "";
            //控制字数
            for (int i = 0; i < num; i++) {
                // 设置字体旋转角度
                int degree = new Random().nextInt() % 30;
                ch = baseChar.charAt(new Random().nextInt(baseChar.length())) + "";
                sb.append(ch);
                // 正向角度
                g.rotate(degree * Math.PI / 180, x, 20);
                g.drawString(ch, x, 20);
                // 反向角度
                g.rotate(-degree * Math.PI / 180, x, 20);
                x += 30;
            }
            return sb.toString();
        }
    }
    

      生成form表单的jsp页面:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>验证码</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath}/Response/ResoultServlet" method="post">
        <label for="yan">验证码</label>
        <input type="text" name="yan" id="yan">
        <img src="${pageContext.request.contextPath}/Response/Response03" alt="验证码看不清,换一张" id="validateCodeImg" onclick="changeImg()">
        <a href="javascript:void(0)" onclick="changeImg()">看不清,换一张</a>
        <input type="submit" value="提交">
    </form>
    </body>
    <script>
        function changeImg() {
            document.getElementById("validateCodeImg").src="${pageContext.request.contextPath}/Response/Response03?"+Math.random();//在末尾加Math.random()的作用:
    如果两次请求地址一样,服务器只会处理第一次请求,第二次请求返回内容和第一次一样。或者说如果地址相同,第一次请求时,将自动缓存,导致第二次不会重复请求了。Math.random()是调用javascript语法中的数学函数,能够产生随机数。
    末尾加Math.random()使每次请求地址不相同,服务器每次都去做不同的响应。也可以使用new date()时间戳的形式作为参数传递。 } </script> </html>

      表单校验的java文件:

    package Response;
    
    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.io.IOException;
    
    /**服务端对手偶到的验证码进行验证*/
    @WebServlet(name = "ResoultServlet", urlPatterns = {"/Response/ResoultServlet"})
    public class ResoultServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置头部和信息防止乱码
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            String clientCheckcode = request.getParameter("yan").toUpperCase();//接受客户端提交上来的参数(使用toUpperCase()可以实现不区分大小写的操作)
            String serverCheckcode = (String) request.getSession().getAttribute("checkcode");//从session中提取验证码
            if(clientCheckcode.equals(serverCheckcode)){
                response.getWriter().write("验证码正确,通过");
            }else{
                response.getWriter().write("验证码错误,失败");
            }
        }
    }
    

      效果:

  • 相关阅读:
    Messy Code in Windows Server 2008 R2 English Edition
    Office Web Apps Server(1)
    How to add a webpart to your website
    How to Upload multiple files to documentLibrary in one time
    [刘阳Java]_SpringMVC文件上传第1季_第10讲
    [刘阳Java]_SpringMVC访问静态资源_第9讲
    react单组件 渲染页面
    react组件传值传方法
    react组件选项卡demo
    react组件
  • 原文地址:https://www.cnblogs.com/mmykdbc/p/9040672.html
Copyright © 2020-2023  润新知