1. 程式人生 > >SpringBoot註冊登入(二):註冊---驗證碼kaptcha的實現

SpringBoot註冊登入(二):註冊---驗證碼kaptcha的實現

SpringBoot註冊登入(一):User表的設計點選開啟連結

      SpringBoot註冊登入(三):註冊--驗證賬號密碼是否符合格式及後臺完成註冊功能點選開啟連結

     SpringBoot註冊登入(四):登入功能--密碼錯誤三次,需要等待2分鐘才能登入,固定時間內不能登入點選開啟連結

SpringBoot註冊登入(五):登入功能--Scheduling Tasks定時作業,用於某個時間段允許/不允許使用者登入點選開啟連結

      SpringBoot(六):攔截器--只允許進入登入註冊頁面,沒登入不允許檢視其它頁面點選開啟連結


      SpringBoot--mybatis--ajax--模態框--log:註冊、登入、攔截器、檔案系統原始碼

點選開啟連結         

注意:要在啟動類加上自己編寫的配置檔案,在本例中的配置檔案為mykaptcha.xml

@ImportResource(locations={"classpath:mykaptcha.xml"})  

①先引入jar

		<!-- begin:kaptcha驗證碼 -->
		<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->  
		<dependency>  
  			  <groupId>com.github.penggle</groupId>  
  			  <artifactId>kaptcha</artifactId>  
 			  <version>2.3.2</version>  
		</dependency>  
		<!-- end:kaptcha驗證碼 -->

②新建配置檔案mykaptcha.xml


程式碼如下:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <!--Border around kaptcha. Legal values are yes or no. -->
                        <prop key="kaptcha.border">no</prop>
                        <!--Color of the border. Legal values are r,g,b (and optional alpha) or white,black,blue. -->
                        <prop key="kaptcha.border.color">red</prop>
                        <!--Thickness of the border around kaptcha. Legal values are > 0. -->
                        <prop key="kaptcha.border.thickness">5</prop>
                        <!--Width in pixels of the kaptcha image. -->
                        <prop key="kaptcha.image.width">80</prop>
                        <!--Height in pixels of the kaptcha image. -->
                        <prop key="kaptcha.image.height">30</prop>
                        <!--The image producer. -->
                        <prop key="kaptcha.producer.impl">com.google.code.kaptcha.impl.DefaultKaptcha </prop>
                        <!--The text producer. -->
                        <prop key="kaptcha.textproducer.impl">com.google.code.kaptcha.text.impl.DefaultTextCreator</prop>
                        <!--The characters that will create the kaptcha. -->
                        <prop key="kaptcha.textproducer.char.string">abcde2345678gfynmnpwx </prop>
                        <!--The number of characters to display. -->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!--A list of comma separated font names. -->
                        <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop>
                        <!--The size of the font to use. -->
                        <prop key="kaptcha.textproducer.font.size">20</prop>
                        <!--The color to use for the font. Legal values are r,g,b. -->
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <!--The noise producer. -->
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise </prop>
                        <!--The noise color. Legal values are r,g,b. -->
                        <prop key="kaptcha.noise.color">black</prop>
                        <!--The obscurificator implementation. -->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
                        <!--The background implementation. -->
                        <prop key="kaptcha.background.impl">com.google.code.kaptcha.impl.DefaultBackground</prop>
                        <!--Ending background color. Legal values are r,g,b. -->
                        <prop key="kaptcha.background.clear.to">white</prop>
                        <!--The word renderer implementation. -->
                        <prop key="kaptcha.word.impl">com.google.code.kaptcha.text.impl.DefaultWordRenderer</prop>
                        <!--The value for the kaptcha is generated and is put into the HttpSession. This is the key value for that item in the session. -->
                        <prop key="kaptcha.session.key">KAPTCHA_SESSION_KEY</prop>
                        <!--The date the kaptcha is generated is put into the HttpSession. This is the key value for that item in the session. -->
                        <prop key="kaptcha.session.date">KAPTCHA_SESSION_DATE</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean> 
  
</beans>  

③新建兩個Controller

NewKaptchaController:點選圖片更換驗證碼

package com.fxy.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class NewKaptchaController {

	/**
	 * ClassName: CaptchaImageCreateController
	 * Function: 生成驗證碼Controller.
	 * date: 
	 *
	 * @author 
	 */
	
	    private Producer captchaProducer = null;

	    @Autowired
	    public void setCaptchaProducer(Producer captchaProducer){
	        this.captchaProducer = captchaProducer;
	    }

	    @RequestMapping("kaptcha.jpg")
	    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
	        // Set to expire far in the past.
	        response.setDateHeader("Expires", 0);
	        // Set standard HTTP/1.1 no-cache headers.
	        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
	        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	        // Set standard HTTP/1.0 no-cache header.
	        response.setHeader("Pragma", "no-cache");

	        // return a jpeg
	        response.setContentType("image/jpeg");

	        // create the text for the image
	        String capText = captchaProducer.createText();

	        // store the text in the session
	        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

	        // create the image with the text
	        BufferedImage bi = captchaProducer.createImage(capText);

	        ServletOutputStream out = response.getOutputStream();

	        // write the data out
	        ImageIO.write(bi, "jpg", out);
	        try {
	            out.flush();
	        } finally {
	            out.close();
	        }
	        return null;
	    }
}

KaptchaController:校驗驗證碼是否正確

package com.fxy.controller;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class KaptchaController {
	private static  final transient Logger log = Logger.getLogger(KaptchaController.class);
	    /**
	     * @Title: loginCheck
	     * @param request
	     * @param kaptchaReceived
	     * @return String
	     * @Description:  驗證碼登入
	     * @author: fxy
	     * @date: 2017年11月21日
	     */
	    @RequestMapping(value = "kaptcha", method = RequestMethod.POST)
	    @ResponseBody
	    public String loginCheck(HttpServletRequest request,
//	            @RequestParam(value = "username", required = true) String username,
//	            @RequestParam(value = "password", required = true) String password,
	            @RequestParam(value = "kaptcha", required = true) String kaptchaReceived){
	        //使用者輸入的驗證碼的值
	        String kaptchaExpected = (String) request.getSession().getAttribute(
	                com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

	        //校驗驗證碼是否正確
	        if (kaptchaReceived == null || !kaptchaReceived.equals(kaptchaExpected)) {
	        	 log.info("驗證碼錯了");
	        	return "kaptcha_error";//返回驗證碼錯誤
	        }
	        //校驗使用者名稱密碼
	        // ……
	        // ……
	        log.info("驗證碼對了");
	        return "success"; //校驗通過返回成功
	    }
	    
	    
}

④register.html的程式碼(包含接下來註冊功能的前端驗證內容)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用者註冊頁面</title>
<script src="webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet"
	href="webjars/bootstrap/3.3.5/css/bootstrap.min.css" />
<script type="text/javascript" src="/js/kaptcha.js"></script>
<script type="text/javascript" src="/js/validate.js"></script>
<script type="text/javascript" src="/js/register.js"></script>
</head>
<body>
<!-- begin:新增一個登錄檔單 -->
	<div>
		<form id="insert_modal" class="form-horizontal">
			<div class="col-sm-10">
				<input type="text" class="form-control" id="insert_name"
					name="name" placeholder="請輸入賬號"/> <span
					class="help-block"></span>
			</div>
			<div class="col-sm-10">
				<input type="password" class="form-control" id="insert_password"
					name="password" placeholder="請輸入密碼"/> <span
					class="help-block"></span>
			</div>
			
			<!-- begin:驗證碼 -->
			<div class="col-sm-10">
				<input type="text" class="form-control" id="kaptcha" name="kaptcha"
					placeholder="請輸入驗證碼" style="color: #000000;" /><span
					class="help-block"></span> <img
					src="kaptcha.jpg" width="200" id="kaptchaImage" title="看不清,點選換一張" />
				<small>看不清,點選換一張</small>
				<button type="button" class="btn btn-primary" id="user_insert_btn">註冊</button>
			</div>
			<!-- end:驗證碼 -->
			
		</form>
	</div>
</body>
</html>

⑤ js檔案的解釋


kaptcha.js:驗證碼的js檔案

$(function() {
	$('#kaptchaImage').click(function() {
		$(this).attr('src', 'kaptcha.jpg?' + Math.floor(Math.random() * 100));
	});

	$('#kaptcha').bind({
		focus : function() {
			//            if (this.value == this.defaultValue){ 
			//                this.value=""; 
			//            } 
		},
		blur : function() {
			//var paramsTime = $("#kaptcha").val();
			var paramsTime = {
				kaptcha : this.value
			};
			$.ajax({
				url : "kaptcha",
				data : paramsTime,
				type : "POST",
				success : function(data) {
					if (data == "kaptcha_error") {
						//顯示驗證碼錯誤資訊
						show_validate_msg("#kaptcha", "error", "驗證碼錯了");
						//禁用按鈕
						$('#user_insert_btn').attr('disabled',"true");
					}else{
						//顯示驗證碼正確資訊
						show_validate_msg("#kaptcha", "success", "驗證碼正確");
						$('#user_insert_btn').removeAttr("disabled");
					}
						
				}
			});
		}
	});
});