用户登录加上验证码

用的工具是idea:

加入dependencies

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.9</version>
  </dependency>
  <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>
  <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
  </dependency>
  <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
  </dependency>
  <dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.13</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.3.2.Final</version>
  </dependency>
  <dependency>
    <groupId>org.jboss.logging</groupId>
    <artifactId>jboss-logging</artifactId>
    <version>3.1.0.CR2</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.2</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.0</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.25</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.13.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.0</version>
  </dependency>
  <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.0.0.GA</version>
  </dependency>
  <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-catalina</artifactId>
    <version>8.0.52</version>
  </dependency>
  <dependency>
    <groupId>xerces</groupId>
    <artifactId>xmlParserAPIs</artifactId>
    <version>2.6.2</version>
  </dependency>
  <dependency>
    <groupId>xerces</groupId>
    <artifactId>xerces</artifactId>
    <version>2.4.0</version>
  </dependency>
  <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
  </dependency>
</dependencies>

里面会有一些多余的,都是项目里用到的,所以就不一一去除了

 

 

 

验证码的工具类:

package com.dromitory.util;

import javax.imageio.ImageIO;
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.util.Random;

/**
 * 验证码生成类
 * Created by zhm on 2017/9/30.
 */
public class RandomValidateCode {
    public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key
    //private String randString = "0123456789";//随机产生只有数字的字符串 private String
    private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串
    //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串
    private int width = 95;// 图片宽
    private int height = 25;// 图片高
    private int lineSize = 40;// 干扰线数量
    private int stringNum = 4;// 随机产生字符数量
    private Random random = new Random();

    /*
     * 获得字体
     */
    private Font getFont() {
        return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
    }

    /*
     * 获得颜色
     */
    private Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }

    /**
     * 生成随机图片
     */
    public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
        g.setColor(getRandColor(110, 133));
        // 绘制干扰线
        for (int i = 0; i <= lineSize; i++) {
            drowLine(g);
        }
        // 绘制随机字符
        String randomString = "";
        for (int i = 1; i <= stringNum; i++) {
            randomString = drowString(g, randomString, i);
        }
        //将生成的随机字符串保存到session中,而jsp界面通过session.getAttribute("RANDOMCODEKEY"),
        //获得生成的验证码,然后跟用户输入的进行比较
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, randomString);
        g.dispose();
        try {
            // 将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 绘制字符串
     */
    private String drowString(Graphics g, String randomString, int i) {
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
                .nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(randString
                .length())));
        randomString += rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13 * i, 16);
        return randomString;
    }

    /*
     * 绘制干扰线
     */
    private void drowLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }

    /*
     * 获取随机的字符
     */
    public String getRandomString(int num) {
        return String.valueOf(randString.charAt(num));
    }
}

 

 

 

JSP页面:

<script type="text/javascript">
function genTimestamp() {
    var time = new Date();
    return time.getTime();
}

function changeImage() {
    $('#verifyCodeImage').attr('src','${pageContext.request.contextPath }/getVerify?timestamp=' + genTimestamp());
}
</script>

 

 

<input type="text" id="user_input_verifyCode" name="user_input_verifyCode" placeholder="验证码" maxlength="4">
<img src="${pageContext.request.contextPath }/getVerify" id="verifyCodeImage" onclick="javascript:changeImage()" title="看不清? 点击更换">
<br>



LoginController里面:
/**
 * 登录页面生成验证码
 */
@RequestMapping("getVerify")
public void getVerify(HttpServletRequest request, HttpServletResponse response){
   response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
   response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
   response.setHeader("Cache-Control", "no-cache");
   response.setDateHeader("Expire", 0);
   RandomValidateCode randomValidateCode = new RandomValidateCode();
   try {
      randomValidateCode.getRandcode(request, response);//输出验证码图片方法
   } catch (Exception e) {
      e.printStackTrace();
   }
}



@RequestMapping(value="/dologin.html",method=RequestMethod.POST)
public String doLogin(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password,@RequestParam(value = "userType")   String userType,@RequestParam(value = "user_input_verifyCode")  String user_input_verifyCode,HttpServletRequest request,HttpSession session) {
   logger.debug("doLogin====================================");
   //调用service方法,进行用户匹配
   String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
   String inputVerifyCode=user_input_verifyCode;
   System.out.println("用户输入的验证码值------>"
         + inputVerifyCode);
   System.out.println("Session中的验证码值------>"
         + random);
 //比较用户输入的验证和产生的验证码是否一样,如果一样的话就可以去数据搜索这个用户在比较密码
   if(inputVerifyCode.equalsIgnoreCase(random)){   

....................................
}
}

 

 

:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以在登录页面中添加一个验证码输入框和一个图片元素,验证码图片可以使用 JavaScript 生成,当用户输入验证码并提交表单时,你可以验证验证码是否正确。以下是示例代码: HTML: ```html <form> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br> <label for="code">验证码:</label> <input type="text" id="code" name="code"><br> <img id="captcha" src=""> <br> <button type="submit">登录</button> </form> ``` JavaScript: ```javascript // 生成验证码 function generateCaptcha() { var code = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 6; i++) { code += possible.charAt(Math.floor(Math.random() * possible.length)); } return code; } // 更新验证码图片 function updateCaptcha() { var captchaImg = document.getElementById("captcha"); var captcha = generateCaptcha(); captchaImg.src = "captcha.php?code=" + captcha; return captcha; } // 验证验证码 function validateCaptcha() { var captcha = document.getElementById("code").value; var valid = captcha === updateCaptcha(); if (!valid) { alert("验证码错误!"); } return valid; } // 初始化验证码 updateCaptcha(); // 提交表单时验证验证码 var form = document.querySelector("form"); form.addEventListener("submit", function(event) { if (!validateCaptcha()) { event.preventDefault(); } }); ``` 这段 JavaScript 代码会在页面加载时生成一个验证码图片,并在用户输入验证码后验证验证码是否正确。你需要在服务器端实现一个 captcha.php 脚本,该脚本接受一个 code 参数,并生成一个包含验证码的图片。你还需要在服务器端验证用户输入的验证码是否正确。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值