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");
					}
						
				}
			});
		}
	});
});

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值