SpringBoot_Vue3 "Hello World" Project Getting Started Tutorial

1 Introduction

The front-end and back-end separation mode allows back-end and front-end developers to focus on their areas of expertise, and allows front-end and back-end business logic to be highly decoupled. This article starts with a simple case to explain the use spring bootand vue3how to separate the front and back ends.

There are two modes of front-end and back-end separation 2:

  • Logical separation : front and rear separation in a project. The overall structure of the project is still MVCa model, which is suitable for small projects.
  • Physical separation : Separate front-end and back-end projects. Because it is a different project, it will involve issues such as remote calls, and is suitable for medium and large projects. The back-end project is only APIa provider, which can serve the front-end projects of different platforms, such as the front-end projects of the web version and WeChat applet version.

This article will use to Spring Boot、Vue3、Elemnet Plusbuild 2this .

No matter which detached mode is used, the backend APIis the same. Therefore, this article first builds the back-end service project.

2. Spring Boot API

The back-end project is also called the server-side, which is mainly for providing API, and the application and display of data is in charge of the front-end. The development tool for the back-end project in this article is IDEA, of course, you can also choose other development tools, the relational database system is mysql.

2.1 Create a project

open IDEA. Create a new project MyBooknamed Spring Boot.

1.png

Select spring bootthe version 2.7.12, and select the following dependent packages:

  • Spring Boot DevTools
  • LomBok
  • Spring Web
  • MyBatis Framework
  • MySql Driver

After confirmation, the initial structure of the project is shown in the following figure:

2.png

Open the project application.propertiesfile and configure jdbcthe basic information of the project.

#配置数据库连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=UTF-8&serverTimezone=PRC
spring.datasource.username=root
spring.datasource.password=abc123

7.png

2.2 DesignAPI

This project is an infrastructure MVCproject, only one is provided for testing API, and the function is to display all book information.

This project adopts a bottom-up design process, first create a database and design booka table.

Tips:mysql The installation process of the database system will not be explained separately here, and the database is connected to the customer service terminal for use Navicat Premium.

Database Design:

  • Start mysqlthe service, open Navicat Premium. Create bookstorea database named, and create a database table named in the database book, its field structure is as follows:

    field name type Remark
    book_id(编号) int primary key, auto-increment
    book_title(书名) varchar
    book_author(作者) varchar
    book_price(价格) double

3.png

  • Name the table as and insert test data bookinto the table .2

4.png

After the database is designed, start to build the project structure: because the project uses mybatis jdbca framework, build mapperthe layer first.

  • mapperlayer.

mapperBefore creating a new layer, create booka class. Code using lomboksimplified bookclasses.

package com.gk.mybook.bean;
import lombok.*;
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    
    
    private Integer bookId;
    private String bookTitle;
    private String bookAuthor;
    private Double bookPrice;
}

New BookMapperclass: Provides the declaration of the method to query all books.

package com.gk.mybook.mapper;
import com.gk.mybook.bean.Book;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface BookMapper {
    
    
    List<Book> getAllBooks();
}

Write SQLa statement: query all books.

 SELECT book_id,book_title,book_author,book_price from book

sqlDocumentation is written in BookMapper.xmla file, which is stored in the project's resources. In order for the files BookMapperto be found automatically xml, a directory structure of structures resourcesis created within the files .com.gk.mybook.mapper

Tips : It is also possible to customize other locations.

So far, the project structure is shown in the following figure:

5.png

  • BookServiceLayer: business layer.

Define the business layer interface IBookServicelayer and declare functions for the business layer.

package com.gk.mybook.service;
import com.gk.mybook.bean.Book;
import java.util.List;
/*
*书籍业务对象
*/
public interface IBookService {
    
    
    List<Book> getBooks();
}

Build business objects BookService: implement IBookServiceinterfaces, depend on BookMapperobjects.

package com.gk.mybook.service.impl;
import com.gk.mybook.bean.Book;
import com.gk.mybook.mapper.BookMapper;
import com.gk.mybook.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService implements IBookService {
    
    
    @Autowired
    private BookMapper bookMapper;
    @Override
    public List<Book> getBooks() {
    
    
        return this.bookMapper.getAllBooks();
    }
}

At this point, the project structure is shown in the following figure:

6.png

  • The controller layer, and maps the interface outward.
package com.gk.mybook.action;
import com.gk.mybook.bean.Book;
import com.gk.mybook.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/book")
public class BookAction {
    
    
    @Autowired
    private IBookService bookService;
    @RequestMapping("/books")
    List<Book> getBooks(){
    
    
       return this.bookService.getBooks();
    }
}
  • Test interface. In order to simplify the operation, test directly in the browser. Before starting the project, don't forget to add @MappScanannotations in front of the startup class. In fact, the new version spring bootcan omit this annotation.
package com.gk.mybook;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value = {
    
    "com.gk.mybook.mapper"})
public class MybookApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(MybookApplication.class, args);
    }
}

After running the program, open the browser and enter in the address bar http://localhost:8080/book/books. If you can see the following results, it means the server is built successfully.

8.png

3. Vue Project

As mentioned above, front-to-back separation can 2be used in a number of ways.

3.1 Logic separation

Use the framework directly in the pages viewof the layer of the server project .htmlvue

resources->staticCreate a new file in the directory of the backend project index.html. Vue、Element plus、axiosIntroduce dependent libraries in the file .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <title>书籍</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- import JavaScript -->
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/vue-router@4"></script>
</head>
<body>
   <div id="app">
   </div>
</body>
</html>

The project structure is as follows:

9.png

Write the following JScode to display all book information on the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <title>书籍</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- import JavaScript -->
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/vue-router@4"></script>
</head>
<body>
<div id="app">
    <h1>{
   
   {title}}</h1>
    <el-table :data="books">
        <el-table-column v-for="book in cols" :key="book.en"
                         :prop="book.en"
                         :label="book.cn"
                         show-overflow-tooltip align="center" width="160px">
            <template #default="scope">
                {
   
   { scope.row[book.en] }}
            </template>
        </el-table-column>
    </el-table>
</div>
<script>
    const {
      
      createApp} = Vue
    var app = createApp({
      
      
        data() {
      
      
            return {
      
      
                title: "我的书籍",
                cols: [{
      
      "en": "bookId", "cn": "编号"}, {
      
      "en": "bookTitle", "cn": "书名"}],
                books: []
            }
        },
        mounted() {
      
      
            axios
                .get('http://localhost:8080/book/books')
                .then(response => (
                    this.books = response.data
                ))
                .catch(function (error) {
      
       // 请求失败处理
                    console.log(error);
                });
        }
    }).use(ElementPlus).mount('#app')
</script>
</body>
</html>

Test result: run spring bootthe project, open the browser, and input directly http://localhost:8080/index.html. You can see the result as shown in the figure below.

10.png

3.2 Physical separation

Physical separation is a template for front-end and back-end separation in the true sense. In addition to server-side projects, this separation mode also has independent framework-based VUEfront-end projects. A single page can be used in the project VUE, which can truly realize the idea of ​​component programming.

There are many ways to create VUEprojects, and there are many excellent front-end development tools. This article uses HBuildand its project creation wizard to build VUEprojects.

3.2.1 Create a new VUEproject

Open HBuild, create a new project, and choose to use to vitebuild the project. As shown below:

11.png

Newly created projects automatically depend on VUE和vitethe module. You can open the project package.jsonto view related information.

12.png

In order to be able to use axios和 Element Plusthese two module libraries need to be installed in the project.

Right-click the item and choose from the pop-up shortcut menu 使用命名行窗口打开所在目录. HBuildThe window can be seen below 终端.

13.png

To install axiosthe module, enter in command mode:

Tips : axiosFor usage, please refer to the official documentation.

npm install axios

To install element-plusthe module, enter in command mode:

npm install element-plus --save

You can package.jsonview the module's dependency information in the file.

14.png

In order to use element plusthe automatic import function, you also need to install unplugin-vue-components 和 unplugin-auto-importthe plug-in. Enter the following command in command mode to install.

npm install -D unplugin-vue-components unplugin-auto-import

Open vite.config.jsthe file and add the following configuration information:

15.png

In order to achieve axioscross-domain access. It is also necessary to create a new configuration class in the backend project and add the following content.

@Configuration
public class CorsConfig {
    
    
    @Bean
    CorsFilter corsFilter() {
    
    
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(source);
    }
}

As shown below:

16.png

3.2.2 Create the front-end page

Within VUEa project, pages can be reusable components. HelloWorld.vueThis article directly modifies the file that has been created , and also realizes reading all books. The content is as follows:

<script setup>
	import {
      
      
		ref,
		reactive
	} from 'vue'
	import axios from 'axios'
	defineProps({
      
      
		msg: String
	})
	const data = reactive({
      
      
		books: null
	})
	/*
	 * 使用 axios 请求服务器数据
	 */
	const getData = function() {
      
      
		axios({
      
      
			url: 'http://localhost:8080/book/books',
			method: 'get',
			headers: {
      
      
				"Access-Control-Allow-Origin": "*",
			}
		}).then((res) => {
      
      
			data.books = res.data
			console.log(data.books)
		});
	}
</script>
<template>
	<h1>{
   
   { msg }}</h1>
	<el-table :data="data.books" style="width: 100%">
		<el-table-column prop="bookId" label="编号" width="180" />
		<el-table-column prop="bookTitle" label="书名" width="180" />
		<el-table-column prop="bookAuthor" label="作者" />
	</el-table>
	<el-button type="primary" @click="getData">查阅书籍</el-button>
</template>
<style scoped>
	a {
      
      
		color: #42b983;
	}
</style>

17.png

Start the front-end and back-end projects:

npm run dev

Open the browser and enter: in the address bar http://localhost:3000.

18.png

Click to view books:

19.png

4. Summary

Through a case, this article briefly introduces the use spring bootand vue3how to realize the separation of the front and back ends of the project.

Guess you like

Origin blog.csdn.net/y6123236/article/details/131102053