1. 程式人生 > 其它 >Kaptcha驗證碼(springboot後端加vue前端簡單實列)

Kaptcha驗證碼(springboot後端加vue前端簡單實列)

搭建編寫環境

搭建前端環境(vue)

使用cmd建立一個基本的vue專案,並用idea開啟

搭建後端環境(springboot)

在根目錄建立一個Module

選擇spring,並下一步。

勾選Web下的Spring Web。並下一步。

這樣你的後端環境就搭建完成了。

程式碼編寫

後端

第一步:匯入kaptcha依賴

        <!-- 驗證碼 依賴-->
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>

第二步:配置KaptchaConfig(驗證碼影象的一些配置資訊)

package com.example.demo.kaptcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        // 圖片邊框
        properties.setProperty("kaptcha.border", "no");
        // 邊框顏色
        properties.setProperty("kaptcha.border.color", "black");
        //邊框厚度
        properties.setProperty("kaptcha.border.thickness", "1");
        // 圖片寬
        properties.setProperty("kaptcha.image.width", "200");
        // 圖片高
        properties.setProperty("kaptcha.image.height", "50");
        //圖片實現類
        properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
        //文字實現類
        properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
        //文字集合,驗證碼值從此集合中獲取
        properties.setProperty("kaptcha.textproducer.char.string", "01234567890qwertyuiopasdfghjklzxcvbnm");
        //驗證碼長度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //字型
        properties.setProperty("kaptcha.textproducer.font.names", "宋體");
        //字型顏色
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        //文字間隔
        properties.setProperty("kaptcha.textproducer.char.space", "5");
        //干擾實現類
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
        //干擾顏色
        properties.setProperty("kaptcha.noise.color", "blue");
        //干擾圖片樣式
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
        //背景實現類
        properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
        //背景顏色漸變,結束顏色
        properties.setProperty("kaptcha.background.clear.to", "white");
        //文字渲染器
        properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

第三步:生成驗證碼影象的CaptchaController

package com.example.demo.kaptcha;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@Controller
public class CaptchaController {
    @Autowired
    private Producer captchaProducer;

    @Autowired
    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    @RequestMapping("getimg")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        logger.debug("******************驗證碼是: " + code + "******************");

        response.setDateHeader("Expires", 0);

        // 設定標準的HTTP/1.1無快取頭資訊
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // 設定IE擴充套件的HTTP/1.1無快取頭(使用addHeader)
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // 設定標準HTTP/1.0無快取報頭
        response.setHeader("Pragma", "no-cache");

        // 返回一個jpeg
        response.setContentType("image/jpeg");

        // 為影象建立文字
        String capText = captchaProducer.createText();

        // 將文字儲存在會話中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // 用文字建立影象
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        // 匯出資料
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}

上面程式碼看不懂的,去學學IO流!

第四步:後臺登入Controller

package com.example.demo.kaptcha;

import com.google.code.kaptcha.Constants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController

public class login {

    @GetMapping("login")

    public boolean login(HttpServletRequest request, @RequestParam("code") String code) {
        String sessionCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (code.equals(sessionCode)) {
//            驗證正常返回true
            return true;
        } else {
//            驗證失敗返回false
            return false;
        }

    }
}

第五步:跨域配置webconfig

在demo下建立一個config包新增一個webconfig檔案

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class webconfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*"); // 1允許任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允許任何頭
        corsConfiguration.addAllowedMethod("*"); // 3允許任何方法(post、get等)
        corsConfiguration.setAllowCredentials(true);//支援安全證書。跨域攜帶cookie需要配置這個
        corsConfiguration.setMaxAge(3600L);//預檢請求的有效期,單位為秒。設定maxage,可以避免每次都發出預檢請求
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }

第六步:測試

執行專案:

1、獲得圖片

在瀏覽器中輸入:http://localhost:8080/getimg

2、驗證校驗碼

在瀏覽器中輸入:http://localhost:8080/login?code=m83v

假如錯誤

前端

第一步:建立一個network包。並編寫封裝

import axios from 'axios'
// 執行跨域攜帶cookie
axios.defaults.withCredentials = true
export function kaptcha(config) {
    let newVar = axios.create({
        baseURL: 'http://localhost:8080',
        timeout:5000
    });
    return newVar(config);
}

第二步,編寫頁面

我就在vue原有的helloworld.vue的頁面上改,刪除裡面原有的div。

<template>
  <div>
    <h1>影象驗證碼</h1>
    <img src="http://localhost:8080/getimg" @click="replace">
    <br>

    <br>
    <button @click="click">驗證</button>
    <br>
    <a>判斷結果:{{this.$data.message}}</a>
  </div>

</template>



第三步,測試

正確返回true

錯誤返回false

本片注意,跨域問題!!!!