Using SpringBoot+Vue to realize message board

Starting at Enaium's personal blog

Complete source code

1, New Vue project and SpringBoot project

New Vue project

  1. New folder springboot Vue messageboard
  2. Create a Vue project using the vue ui command (requires vue 3.0

Select the directory just now2020-4-20-1 After the name is Vue created, V or lowercase can be changed to uppercase2020-4-20-2 Cancel git initialization2020-4-20-3 Manual configuration2020-4-20-4 cancel2020-4-20-5 open2020-4-20-6 Create project without saving preset2020-4-20-7

New SpringBoot project

  1. Open spring boot Vue message board directory with IDEA

2020-4-20-82020-4-20-9

  1. Create a SpringBoot project

Right click2020-4-20-10 Select Spring Initializr2020-4-20-112020-4-20-12 Choose these four2020-4-20-13 Name changed to SpringBoot2020-4-20-14

2, Back end

Configure 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

Write entity class

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

Entity class 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();//Traverse all messages
    }

    @GetMapping("/postMessage")
    private String postMessage(@RequestParam String author, @RequestParam String message) {
        if(author.replaceAll(" ","").equals("") || message.replaceAll(" ","").equals("")) {
            return "filed";
        }//Judge whether the name and message are empty
        messageRepository.save(new Message((long) (messageRepository.findAll().size() + 1),author,message,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));//Save message to database
        return "success";
    }
}

Resolve cross source requests

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//Override this method
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

3, Front end

Install plug-ins axios and Element UI

Write Home page

<template>
    <div>
        <h1>Message board</h1>
        <el-input
                type="text"
                placeholder="Please enter your name"
                v-model="messageBoard.author"
                maxlength="16"
                show-word-limit
        >
        </el-input>
        <div style="margin: 20px 0;"></div>
        <el-input
                type="textarea"
                placeholder="Please enter a message"
                v-model="messageBoard.message"
                show-word-limit
        >
        </el-input>
        <div style="margin: 20px 0;"></div>
        <el-button type="primary" plain @click="postMessage">Leaving a message.</el-button>
        <el-divider></el-divider>
        <el-table
                :data="messages"
                height="250"
                border
                style="width: 100%">
            <el-table-column
                    prop="id"
                    label="Serial number"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="author"
                    label="Name">
            </el-table-column>
            <el-table-column
                    prop="message"
                    label="Leaving a message.">
            </el-table-column>
            <el-table-column
                    prop="time"
                    label="time"
                    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('Please enter your name');
                    return
                }

                if (this.messageBoard.message === '') {
                    this.$message.error('Please enter a message');
                    return
                }

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

Routing page

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

4, Operation

  1. Running SpringBoot
  2. cd to Vue running with npm run serve

Tags: Programming Vue Spring SpringBoot MySQL

Posted on Mon, 20 Apr 2020 07:59:09 -0700 by idotcom