1. 程式人生 > >使用者登入加上驗證碼

使用者登入加上驗證碼

用的工具是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)){   

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

: