使用 SpringBoot+Vue 實現留言版


首發於Enaium的個人博客


完成源碼

一.新建Vue項目和SpringBoot項目

新建Vue項目

  1. 新建文件夾SpringBoot-Vue-MessageBoard
  2. 創建Vue項目使用vue ui命令(需要vue 3.0

選擇剛才的目錄2020-4-20-1
名字為Vue創建后V還是小寫 創建后可以改為大寫2020-4-20-2
取消git初始化2020-4-20-3
手動配置2020-4-20-4
取消2020-4-20-5
打開2020-4-20-6
創建項目,不保存預設2020-4-20-7

新建SpringBoot項目

  1. 用IDEA打開SpringBoot-Vue-MessageBoard這個目錄

2020-4-20-8
2020-4-20-9

  1. 創建SpringBoot項目

右鍵2020-4-20-10
選擇Spring Initializr2020-4-20-11
2020-4-20-12
選擇這四個2020-4-20-13
名字改為SpringBoot2020-4-20-14

二. 后端

配置application.properties

#Mysql
spring.datasource.url=jdbc:mysql://localhost:3306/enaium?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.format_sql = true
#Server
server.port=8181

寫實體類

package cn.enaium.message.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * Project: message
 * -----------------------------------------------------------
 * Copyright © 2020 | Enaium | All rights reserved.
 */
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Message {
    @Id
    private Long id;
    private String author;
    private String message;
    private String time;
}

實體類Jpa

package cn.enaium.message.repository;

import cn.enaium.message.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Project: message
 * -----------------------------------------------------------
 * Copyright © 2020 | Enaium | All rights reserved.
 */
public interface MessageRepository extends JpaRepository<Message, Long> {
}

Controller

package cn.enaium.message.controller;

import cn.enaium.message.entity.Message;
import cn.enaium.message.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Project: message
 * -----------------------------------------------------------
 * Copyright © 2020 | Enaium | All rights reserved.
 */
@RestController
public class Controller {

    @Autowired
    private MessageRepository messageRepository;

    @RequestMapping("/getMessages")
    private List<Message> getMessages() {
        return messageRepository.findAll();//遍歷所有留言
    }

    @GetMapping("/postMessage")
    private String postMessage(@RequestParam String author, @RequestParam String message) {
        if(author.replaceAll(" ","").equals("") || message.replaceAll(" ","").equals("")) {
            return "filed";
        }//判斷名字和留言是否為空
        messageRepository.save(new Message((long) (messageRepository.findAll().size() + 1),author,message,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));//保存留言到數據庫
        return "success";
    }
}

解決跨源請求問題

2020-4-20-15

package cn.enaium.message.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Project: message
 * -----------------------------------------------------------
 * Copyright © 2020 | Enaium | All rights reserved.
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override//重寫這個方法
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

三. 前端

安裝插件axiosElement UI

2020-4-20-16

2020-4-20-17

Home頁面

<template>
    <div>
        <h1>留言版</h1>
        <el-input
                type="text"
                placeholder="請輸入你的名字"
                v-model="messageBoard.author"
                maxlength="16"
                show-word-limit
        >
        </el-input>
        <div style="margin: 20px 0;"></div>
        <el-input
                type="textarea"
                placeholder="請輸入留言"
                v-model="messageBoard.message"
                show-word-limit
        >
        </el-input>
        <div style="margin: 20px 0;"></div>
        <el-button type="primary" plain @click="postMessage">留言</el-button>
        <el-divider></el-divider>
        <el-table
                :data="messages"
                height="250"
                border
                style="width: 100%">
            <el-table-column
                    prop="id"
                    label="序號"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="author"
                    label="名字">
            </el-table-column>
            <el-table-column
                    prop="message"
                    label="留言">
            </el-table-column>
            <el-table-column
                    prop="time"
                    label="時間"
                    width="160">
            </el-table-column>
        </el-table>
        <el-link type="primary" href="https://github.com/Enaium">By Enaium</el-link>
    </div>
</template>

<script>
    export default {
        name: "Home",
        data() {
            return {
                messageBoard: {
                    author: '',
                    message: ''
                },
                messages: []
            }
        },
        methods: {
            postMessage() {
                if (this.messageBoard.author === '') {
                    this.$message.error('請輸入你的名字');
                    return
                }

                if (this.messageBoard.message === '') {
                    this.$message.error('請輸入留言');
                    return
                }

                axios.get("http://localhost:8181/postMessage?author=" + this.messageBoard.author + "&message=" + this.messageBoard.message).then((t) => {
                    if (t.data === 'success') {
                        this.$message({
                            message: '留言成功',
                            type: 'success'
                        });
                    } else {
                        this.$message.error('留言失敗');
                    }
                })
            }
        },
        created() {
            axios.get("http://localhost:8181/getMessages").then((t) => {
                this.messages = t.data
            })
        }
    }
</script>

路由頁面

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    }
]

const router = new VueRouter({
    mode: 'history',
    routes
})

export default router

四. 運行

  1. 運行SpringBoot
  2. cd 到Vue使用npm run serve運行

2020-4-20-18


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM