SpringBoot+vue 前後端的分離專案筆記 [一] 專案搭建

semlie1994發表於2020-05-15

最近學習研究springboot+vue專案,發現很好用,網上教程比較雜,所以寫下這篇筆記,留作自用。

1、搭建環境

vue安裝:(基本流程已忘,基本是按著這個來的)
教程:安裝VUE教程 - 歸塵2016 - 部落格園
SpringBoot:環境搭建更早,基本只需要具備:java1.8
開發工具都是使用:IDEA

2、Vue專案建立

教程:Springboot Vue Login(從零開始實現Springboot+Vue登入)
這個教程我基本只參考了前半截,沒新增element框架,也沒有使用Springboot搭建不是用這個教程:joy:
建立完成之後用idea開啟,配置好npm之後就可以直接啟動vue:
教程:idea啟動vue專案
如果是按上面教程建立專案,那用idea啟動專案時有個地方要改:

SpringBoot+vue前後端的分離步驟說明,以及相關連結

3、SpringBoot專案建立

可以直接訪問官方網站建立:start.spring.io
也可以用IDEA建立:快速建立springBoot專案
建立之後不要忘了改變埠:
application.properties

server.port=9090

SpringBoot專案在IDEA可以直接啟動
跨域訪問問題在上面教程中有提到,可以參考:Springboot Vue Login(從零開始實現Springboot+Vue登入)
出現的問題:pom.xml中的jar包沒載入出來,解決辦法就是新增映象
教程:maven國內映象配置

4、Vue與SpringBoot簡單互動(驗正碼)

Vue方面

1、axios配置
request.js

import axios from 'axios' //引入 axios
// 建立 axios 例項
const service = axios.create({
    baseURL: 'http://192.168.1.129:9090/', // api 的 base_url
    timeout: 15000, // 請求超時時間
});

main.js

import axios from './utils/request';
Vue.prototype.$axios = axios;

2、登入頁
login.vue

<template>
    <div class="page">
        <form :model="loginForm" class="form form-horizontal" action="#/" method="post">
            <input id="text"  type="text" v-model="loginForm.username"  placeholder="請輸入賬號"  name="username">
            <input id="pass" type="password" v-model="loginForm.password" placeholder="請輸入密碼"  name="password" >
            <label class="hq"><input id="text2" type="text" placeholder="請輸入驗證碼" v-model="loginForm.inputCode" name="captcha">
                <img class="rzm"  :src='imgcode' @click="getIdentifyingCode(true)" >
            </label>
            <p class="submit">登入</p>
        </form>
    </div>
</template>
<script>
    export default {
        name: "login1",
        data(){
            return{
                imgcode:'',
                code:'',
                loginForm:{
                    username:'',
                    password:'',
                    inputCode:'',
                },
                userToken:''
            }
        },
        created:function() {
            this.getIdentifyingCode();
        },
        methods:{
            /*獲取驗證碼*/
            getIdentifyingCode: function () {
                this.$axios.get('user/getImgCode')
                    .then((response) => {
                        this.imgcode = response.data.data;
                        this.code = response.data.imgCode;
                        // console.log(this.code)
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        }

    }
</script>

SpringBoot方面(教程忘記儲存,直接貼上程式碼吧)

ImgValidateCodeUtil.java

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ImgValidateCodeUtil {
    private static Random random = new Random();
    /**
     * 驗證碼的寬
     */
    private static int width = 160;
    /**
     * 驗證碼的高
     */
    private static int height = 40;
    /**
     * 驗證碼的干擾線數量
     */
    private static int lineSize = 30;
    /**
     * 驗證碼詞典
     */
    private static String randomString = "0123456789abcdefghijklmnopqrstuvwxyz";
    /**
     * 獲取字型
     * @return
     */
    private static Font getFont() {
        return new Font("Times New Roman", Font.ROMAN_BASELINE, 40);
    }
    /**
     * 獲取顏色
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandomColor(int fc, int bc) {
        fc = Math.min(fc, 255);
        bc = Math.min(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 - 12);
        return new Color(r, g, b);
    }
    /**
     * 繪製干擾線
     * @param g
     */
    private static void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(20);
        int yl = random.nextInt(10);
        g.drawLine(x, y, x + xl, y + yl);
    }
    /**
     * 獲取隨機字元
     * @param num
     * @return
     */
    private static String getRandomString(int num) {
        num = num > 0 ? num : randomString.length();
        return String.valueOf(randomString.charAt(random.nextInt(num)));
    }
    /**
     * 繪製字串
     * @param g
     * @param randomStr
     * @param i
     * @return
     */
    private static String drawString(Graphics g, String randomStr, int i) {
        g.setFont(getFont());
        g.setColor(getRandomColor(108, 190));
        String rand = getRandomString(random.nextInt(randomString.length()));
        randomStr += rand;
        g.translate(random.nextInt(3), random.nextInt(6));
        g.drawString(rand, 40 * i + 10, 25);
        return randomStr;
    }
    /**
     * 生成隨機圖片,返回 base64 字串
     * @param
     * @return
     */
    public static Map<String, String> getImgCodeBaseCode(int length) {
        Map<String, String> result = new HashMap<>();
        // BufferedImage類是具有緩衝區的Image類,Image類是用於描述影像資訊的類
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, width, height);
        // 獲取顏色
        g.setColor(getRandomColor(105, 189));
        // 獲取字型
        g.setFont(getFont());
        // 繪製干擾線
        for (int i = 0; i < lineSize; i++) {
            drawLine(g);
        }
        // 繪製隨機字元
        String randomCode = "";
        for (int i = 0; i < length; i++) {
            randomCode = drawString(g, randomCode, i);
        }
//        System.out.println("驗證碼是:" + randomCode);
        g.dispose();
        result.put("imgCode", randomCode);
        String base64Code = "";
        try {
            //返回 base64
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", bos);
            byte[] bytes = bos.toByteArray();
            Base64.Encoder encoder = Base64.getEncoder();
            base64Code = encoder.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("data", "data:image/png;base64," + base64Code);
        return result;
    }
}

LoginControll.java

@RestController
@SpringBootApplication
@RequestMapping("/user")
public class LoginControll {
    //生成驗證碼
    @RequestMapping(value = "/getImgCode")
    @ResponseBody
    public Map<String, String> getImgCode() {
        Map<String, String> result = new HashMap<>();
        try {
            result = ImgValidateCodeUtil.getImgCodeBaseCode(4);
        } catch (Exception e) {
            System.out.println(e);
        }
        return result;
    }
}

結果:
SpringBoot+vue 前後端的分離步驟說明,以及相關連結

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章