1. 程式人生 > >Java——使用springboot2.0+kaptcha進行驗證碼校驗

Java——使用springboot2.0+kaptcha進行驗證碼校驗

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.captcha</groupId>
	<artifactId>captcha</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>captcha</name>
	<description>Captcha project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- web層 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 頁面渲染jar包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!--kaptcha驗證碼生成器 -->
		<dependency>
			<groupId>com.github.axet</groupId>
			<artifactId>kaptcha</artifactId>
			<version>0.0.9</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

響應的R類

package com.captcha.demo;

import java.util.List;

public class R  {
    private String retCode;
    private String retMsg;
    private Object retBean;
    private List<Object> retBeans;

    public String getRetCode() {
        return retCode;
    }

    public void setRetCode(String retCode) {
        this.retCode = retCode;
    }

    public String getRetMsg() {
        return retMsg;
    }

    public void setRetMsg(String retMsg) {
        this.retMsg = retMsg;
    }

    public Object getRetBean() {
        return retBean;
    }

    public void setRetBean(Object retBean) {
        this.retBean = retBean;
    }

    public List<Object> getRetBeans() {
        return retBeans;
    }

    public void setRetBeans(List<Object> retBeans) {
        this.retBeans = retBeans;
    }
}

配置的檔案application.yml

spring:
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    suffix: .html
    encoding: UTF-8
    mode: LEGACYHTML5
    cache: false

h5頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登陸</title>
</head>
<body>
<div class='loginDiv'>
    <h1 align="center">歡迎登陸</h1>
        <form  action="userLogin" method="get">               
        <div >
            <label >驗證碼</label>
            <div >
                <input type="text" name="kaptcha" placeholder="請輸入驗證碼" autocomplete="off">
                <img src="captcha.jpg" onclick="refresh(this)" >
            </div>
        </div>
        <div >
            <div >
                <button >立即提交</button>
            </div>
        </div>
    </form>
</div>
<script>
    function refresh(obj) {
        obj.src = "captcha.jpg?t=" + new Date().getMilliseconds();
    }

</script>

</body>
</html>

需注入的依賴類

package com.captcha.demo;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha defaultKaptcha(){

        Properties properties = new Properties();
        properties.setProperty("kaptcha.border","no");
        properties.setProperty("kaptcha.textproducer.font.color","black");
        properties.setProperty("kaptcha.textproducer.char.space","5");
        Config config = new Config(properties);

        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

最後是web層的Controller Demo

package com.captcha.demo;

import java.awt.image.BufferedImage;
import java.io.IOException;

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.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
public class CaptchDemo {
	@Autowired
	private DefaultKaptcha defaultKaptcha;

	@RequestMapping("/captcha.jpg")
	@ResponseBody
	public R applyCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		R r = new R();

		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字驗證碼
		String text = defaultKaptcha.createText();
		// 生成圖片驗證碼
		BufferedImage image = defaultKaptcha.createImage(text);
		// 儲存到session
		request.getSession().setAttribute("CHECK CODE", text);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		return r;
	}

	@ResponseBody
	@RequestMapping(value = "/userLogin")
	public String userLogin(HttpServletRequest request) {

		String kaptcha = request.getParameter("kaptcha");

		String s = request.getSession().getAttribute("CHECK CODE").toString();
		if (StringUtils.isEmpty(kaptcha) || !s.equals(kaptcha)) {
			return "failure";
		}
		return "success";
	}

	@RequestMapping(value = "/login")
	public String login() {
		return "/login";
	}
}

以上就是使用springboot建立的驗證碼生成與驗證全過程,如果有什麼問題可在下面評論提出,謝謝!