验证码的实现

2023-10-12 14:32:54 浏览数 (2)

验证码的实现

前端:

代码语言:javascript复制
<div class="r">
	<!-- 提示信息 -->  
    <input type="hidden" id="tip" value="${tip}"/>
    <h2 title="登录移动商城">登录移动商城</h2>
    <form id="jvForm" action="${path}/user/login.do" method="post">
        <ul class="uls form">
            <li id="errorName" class="errorTip" style="display:none">${error}</li>
            <li><label for="username">用户名:</label>
                <span class="bg_text">
   <input type="text" id="username" name="username" vld="{required:true}" maxLength="100"/>
</span>
            </li>
            <li><label for="password">密 码:</label>
                <span class="bg_text">
   <input type="password" id="password" name="password" maxLength="32" vld="{required:true}"/>
</span>
            </li>
            <li><label for="captcha">验证码:</label>
                <span class="bg_text small">
   <input type="text" id="captcha" name="captcha" maxLength="7" vld="{required:true}"/>
</span>
                <img id="captchaImage" src="${path}/user/getImage.do" onclick="changeImage()"
                     class="code" alt="换一张"/><a href="javascript:void(0);"
                                                onclick="changeImage()" title="换一张">换一张</a>
            </li>
            <li class="gray"><label for="">&nbsp;</label><input type="checkbox" name=""/>30天内免登录(公共电脑勿用)</li>
            <li><label for="">&nbsp;</label><input type="submit" value="登 录" class="hand btn66x23"/><a href="#"
                                                                                                       title="忘记密码?">忘记密码?</a>
            </li>
            <li class="alg_c dev gray">还不是移动商城会员?<a href="../passport/register.html" title="免费注册">免费注册</a></li>
        </ul>
    </form>
</div>

js文件:

代码语言:javascript复制
$(function () {
    $(".bg_text input").blur(function () {
        //获得离开焦点的值
        var val = $(this).val();
        val = $.trim(val);
        //取name属性的值
        var inputName = $(this).attr("name");
        if (val==null||val=="") {
            if(inputName=="username"){
                $("#errorName").html("请输入用户名");
            }else if (inputName=="password") {
                $("#errorName").html("请输入密码");
            }else if (inputName=="captcha") {
                $("#errorName").html("请输入验证码");
            }
            //显示500毫秒
            $("#errorName").show(500);
        }else {
            $("#errorName").hide(500);
        }
    })
    //验证码错误提示信息
    var tip=$("#tip").val();
    if(tip=="captcha_error") {
        $("#errorName").html("验证码错误");
        $("#errorName").show(500);
    }else if(tip=="userpwd_error"){
        $("#errorName").html("用户名或密码错误");
        $("#errorName").show(500);
    }
})
function changeImage() {
    //有的浏览器在请求url相同的时候会不调用后台 从缓存中取 因此加上时间戳参数
    var cPath = path "/user/getImage.do?date=" new Date();
    $("#captchaImage").attr("src",cPath);
}

后台:

代码语言:javascript复制
/**
 * 生成验证码
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping("/getImage.do")
public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
    System.out.println("#######################生成数字和字母的验证码#######################");
    BufferedImage img = new BufferedImage(68, 22,

            BufferedImage.TYPE_INT_RGB);

    // 得到该图片的绘图对象

    Graphics g = img.getGraphics();

    Random r = new Random();

    Color c = new Color(200, 150, 255);

    g.setColor(c);

    // 填充整个图片的颜色

    g.fillRect(0, 0, 68, 22);

    // 向图片中输出数字和字母

    StringBuffer sb = new StringBuffer();

    char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

    int index, len = ch.length;

    for (int i = 0; i < 4; i  ) {

        index = r.nextInt(len);

        g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt

                (255)));

        g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));
        // 输出的  字体和大小

        g.drawString(""   ch[index], (i * 15)   3, 18);
        //写什么数字,在图片 的什么位置画

        sb.append(ch[index]);

    }

    //验证码存储在session中来进行校验
    request.getSession().setAttribute("piccode", sb.toString());

    ImageIO.write(img, "JPG", response.getOutputStream());
}


/**
 * 登录验证并跳转
 * @param username
 * @param password
 * @param captcha
 * @param session
 * @param model
 * @return
 */
@RequestMapping("/login.do")
public String login(String username, String password, String captcha, HttpSession session,Model model) {
    //获得sesion中正确的验证码
    String captchaSession = (String) session.getAttribute("piccode");
    if (!StringUtils.equalsIgnoreCase(captchaSession,captcha)) {
        //写入错误信息
        model.addAttribute("tip","captcha_error");
        return "passport/login";
    }
    password = MD5.GetMD5Code(password);
    Map<String,String> map = new HashMap<>();
    map.put("username",username);
    map.put("password",password);
    TsPtlUser tsPtlUser = tsPtlUserService.selectUserByUsernameAndPwd(map);
    if(tsPtlUser==null) {
        //在数据库中为查到用户信息
        model.addAttribute("tip","userpwd_error");
        return "passport/login";
    }
    //用户信息写入session
    session.setAttribute("user",tsPtlUser);
    // 重定向到商品首页
    return "redirect:/item/toIndex.do";
}

MD5工具类:

代码语言:javascript复制
/**
 * describe:Md5加密
 *
 * @author xiepanpan
 * @date 2018/11/14
 */
public class MD5 {

    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public MD5() {
    }

    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet  = 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1]   strDigits[iD2];
    }

    private static String byteToNum(byte bByte) {
        int iRet = bByte;
        System.out.println("iRet1="   iRet);
        if (iRet < 0) {
            iRet  = 256;
        }
        return String.valueOf(iRet);
    }

    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i  ) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    public static void main(String[] args) {
        MD5 getMD5 = new MD5();
        System.out.println(getMD5.GetMD5Code("123456"));
    }
}

0 人点赞