前端+后端:验证码实现

参考
https://www.cnblogs.com/makexu/articles/5314314.html

package com.mi.servlet;

import com.mi.domain.resp.BaseResp;

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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@WebServlet(name = "CheckCodeServlet",urlPatterns = "/checkCode")

//优先匹配servlet,如果能够找到servlet则直接执行servlet
//如果没有servlet只有静态资源,则直接返回静态资源
//如果静态资源也没有,则出现404
//@WebServlet("/a.html")
//a.html

public class CheckCodeServlet extends BaseServlet {

    //kaptcha验证码框架
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method=req.getParameter("method");
        if ("getMa".equals(method)){
            getMa(req,res);
        }else if("checkMa".equals(method)){
            checkMa(req,res);
        }
    }

    private void checkMa(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String yanzhenStr=request.getParameter("yanzheng");
        String yanzhen=(String) request.getSession().getAttribute("yanzhen");
        System.out.println("验证码1"+yanzhenStr);
        System.out.println("验证码2"+yanzhen);

        BaseResp baseResp=new BaseResp();
        if (yanzhenStr==null||"".equals(yanzhenStr)){
            baseResp.setCode(0);
            baseResp.setMsg("验证码不能为空");
            out.print(gson.toJson(baseResp));
        }

        if (yanzhen.equals(yanzhenStr)){
            baseResp.setCode(1);
            out.print(gson.toJson(baseResp));
        }else {
            baseResp.setCode(0);
            baseResp.setMsg("验证码不正确");
            out.print(gson.toJson(baseResp));
        }
        out.print(gson.toJson(baseResp));
    }

    private void getMa(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        //验证码的绘制需要借助java   awt包下的一些绘制相关的类
        Random r = new Random();
        //1.先构建一个画板对象--内存中的画板对象,最后需要借助响应流写出到客户端
        BufferedImage bufferedImage = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
        //2.获取画笔对象
        Graphics g = bufferedImage.getGraphics();
        //设置画笔的颜色
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        //填充背景色
        g.drawRect(0, 0, 100, 30);
        //3.绘制字符串
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        //设置字体
        g.setFont(new Font(Font.SERIF, Font.BOLD, 20));
        //将字符串画上去
        String yanzhen=getCode(4);
        g.drawString(yanzhen, 20, 20);
//        保存验证码
        HttpSession session=req.getSession();
        session.setAttribute("yanzhen" ,yanzhen);
        System.out.println("验证码初"+yanzhen);
        //4.绘制噪音线和噪音点
        for (int i = 1; i <= 10; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));

        }

        //将字符串写出到响应流中
        res.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpeg", res.getOutputStream());
    }

    private static String getCode(int len) {
        Random r = new Random();
        String strs = "3456789abcdefghjkmnpqrstuvwxy";
        String result = "";
        for (int i = 1; i <= len; i++) {
            result += strs.charAt(r.nextInt(strs.length()));
        }
        return result;
    }


}

  var imgObj = document.getElementById("img");
            $("#verifyCanvas").on("click",function () {
                //浏览器存在缓存机制,第一次请求后得到的结果会被缓存起来
                //第二次如果发送了一样的请求,则直接从缓存中获取数据,不会重新访问服务器
                imgObj.src = baseUrl + "checkCode?method=getMa&r=" + new Date().getTime();
            });
 $(function () {
                // 手机号验证
                $("#telnumber").focus(function () {
                    $("#nameinfo").text("");
                })
                $("#telnumber").blur(function () {

                    console.log(this.value);

                    if (this.value.length == 0) {
                        $("#nameinfo").text("手机号不能为空!")
                        $(".tickk").remove();
                    } else if (!rule.test(this.value)) {
                        $("#nameinfo").text("手机号不正确!1开头6-11位")
                        $(".tickk").remove();
                    } else {
                        $("#nameinfo").text("")

                        ajaxCheckUser(this.value)

                    }
                });
                
                //验证码验证
                $("#yanzheng").focus(function () {
                    $("#minfo").text("");
                })
                $("#yanzheng").blur(function () {

                    console.log(this.value);

                    if (this.value.length == 0) {
                        $("#minfo").text("验证码不能为空!")
                        $(".tickk").remove();
                    } else {
                        $("#minfo").text("")

                        ajaxYanzhen(this.value)

                    }
                });
function  ajaxYanzhen(yanzhen) {
                console.log("发起check接口---" + yanzhen)
                $.ajax({
                    url: baseUrl + "/checkCode",
                    data: {"method":"checkMa","yanzheng": yanzhen},
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        console.log(data)
                        if (data.code!=1) {
                            //说明数据库上有这个重名用户了
                            $("#minfo").text(data.msg)

                            return false
                        }else {
                            $("#minfo").text("验证码正确")
                            return true
                        }
                    },
                    error: function (e) {

                    }

                })
            }

你可能感兴趣的:(web)