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 boot
and vue3
how 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
MVC
a 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
API
a 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 Plus
build 2
this .
No matter which detached mode is used, the backend API
is 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 MyBook
named Spring Boot
.
Select spring boot
the 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:
Open the project application.properties
file and configure jdbc
the 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
2.2 DesignAPI
This project is an infrastructure MVC
project, 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 book
a 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 useNavicat Premium
.
Database Design:
-
Start
mysql
the service, openNavicat Premium
. Createbookstore
a database named, and create a database table named in the databasebook
, 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
- Name the table as and insert test data
book
into the table .2
After the database is designed, start to build the project structure: because the project uses mybatis jdbc
a framework, build mapper
the layer first.
mapper
layer.
mapper
Before creating a new layer, create book
a class. Code using lombok
simplified book
classes.
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 BookMapper
class: 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 SQL
a statement: query all books.
SELECT book_id,book_title,book_author,book_price from book
sql
Documentation is written in BookMapper.xml
a file, which is stored in the project's resources
. In order for the files BookMapper
to be found automatically xml
, a directory structure of structures resources
is 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:
BookService
Layer: business layer.
Define the business layer interface IBookService
layer 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 IBookService
interfaces, depend on BookMapper
objects.
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:
- 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
@MappScan
annotations in front of the startup class. In fact, the new versionspring boot
can 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.
3. Vue Project
As mentioned above, front-to-back separation can 2
be used in a number of ways.
3.1 Logic separation
Use the framework directly in the pages view
of the layer of the server project .html
vue
resources->static
Create a new file in the directory of the backend project index.html
. Vue、Element plus、axios
Introduce 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:
Write the following JS
code 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 boot
the project, open the browser, and input directly http://localhost:8080/index.html
. You can see the result as shown in the figure below.
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 VUE
front-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 VUE
projects, and there are many excellent front-end development tools. This article uses HBuild
and its project creation wizard to build VUE
projects.
3.2.1 Create a new VUE
project
Open HBuild
, create a new project, and choose to use to vite
build the project. As shown below:
Newly created projects automatically depend on VUE和vite
the module. You can open the project package.json
to view related information.
In order to be able to use axios和 Element Plus
these two module libraries need to be installed in the project.
Right-click the item and choose from the pop-up shortcut menu 使用命名行窗口打开所在目录
. HBuild
The window can be seen below 终端
.
To install axios
the module, enter in command mode:
Tips :
axios
For usage, please refer to the official documentation.
npm install axios
To install element-plus
the module, enter in command mode:
npm install element-plus --save
You can package.json
view the module's dependency information in the file.
In order to use element plus
the automatic import function, you also need to install unplugin-vue-components 和 unplugin-auto-import
the plug-in. Enter the following command in command mode to install.
npm install -D unplugin-vue-components unplugin-auto-import
Open vite.config.js
the file and add the following configuration information:
In order to achieve axios
cross-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:
3.2.2 Create the front-end page
Within VUE
a project, pages can be reusable components. HelloWorld.vue
This 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>
Start the front-end and back-end projects:
npm run dev
Open the browser and enter: in the address bar http://localhost:3000
.
Click to view books:
4. Summary
Through a case, this article briefly introduces the use spring boot
and vue3
how to realize the separation of the front and back ends of the project.