赞
踩
例如:
// 前端
axios.get('/api/articles').then(response => {
this.articles = response.data
})
// 后端
@GetMapping("/api/articles")
public List<Article> getArticles() {
return articleService.findAll();
}
上述代码实现了:
/api/articles
接口获取文章列表数据实现前后端分离。
前端只关注使用JSON数据更新UI,后端只关注提供JSON数据。
部署方面,前端可以部署到任何webapp上,后端可以部署到任何Java应用服务器。
通过这种方式,我们可以:
根据你提供的需求,可按以下步骤创建Vue项目:
vue create my-blog
选择默认配置(请选择Manually select features)
npm install vue-router vuex axios
import VueRouter from 'vue-router'
const router = new VueRouter({
routes: [
{ path: '/', component: ArticleList }
]
})
export default router
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
})
export default store
import axios from 'axios'
export default {
getArticles() {
return axios.get('/api/articles')
}
}
通过这种方式,我们基本搭建好路由、状态管理和接口调用功能,后续再根据需求完善组件、actions等内容。
ArticleList组件获取文章列表的代码如下:
<template>
<ul>
<li v-for="article in articles">
{{ article.title }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
articles: []
}
},
created() {
this.getArticles()
},
methods: {
async getArticles() {
let { data } = await axios.get('/api/articles')
this.articles = data
}
}
}
</script>
在data
函数中定义articles
数组保存文章数据
在created
生命周期钩子中,调用getArticles
方法获取文章列表
getArticles
方法异步调用接口请求文章列表
接口请求成功后,将响应数据data
赋值给articles
,从而渲染文章列表
主要功能包括:
articles
数据created
钩子中调用接口await
执行异步接口请求articles
渲染列表上述代码实现了:
根据你提供的需求,可按以下步骤定义其他组件:
<template>
<form @submit.prevent="saveArticle">
<input v-model="article.title" />
<textarea v-model="article.content"></textarea>
<button type="submit">保存文章</button>
</form>
</template>
<script>
export default {
data() {
return {
article: {
title: '',
content: ''
}
}
},
methods: {
async saveArticle() {
await axios.post('/api/article', this.article)
this.$router.push('/')
}
}
}
</script>
<template>
<ul>
<li v-for="tag in tags">
{{ tag.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
tags: []
}
},
async created() {
let { data } = await axios.get('/api/tags')
this.tags = data
}
}
</script>
<template>
<ul>
<li v-for="comment in comments">
<p>{{ comment.content }}</p>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
comments: []
}
},
async created() {
let { data } = await axios.get('/api/comments')
this.comments = data
}
}
</script>
通过定义不同的组件,对应处理不同的数据和业务逻辑,我们就可以完整展现页面所需功能。
根据需求,可以按照以下步骤搭建Spring Boot项目:
选择:
Group: com.example
Artifact: demo
Java: 1.8
Packaging: Jar
Dependencies:
在application.properties
添加:
spring.datasource.url= jdbc:mysql://localhost:3306/demo
spring.datasource.username= root
spring.datasource.password= 123456
@Entity
public class Article {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
// getters and setters
}
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
@Service
public class ArticleService {
@Autowired
ArticleRepository articleRepository;
public List<Article> findAll() {
return articleRepository.findAll();
}
}
@GetMapping("/articles")
public List<Article> findAll() {
return articleService.findAll();
}
通过这种方式,我们基于Spring Boot + JPA 就能快速搭建一个连接MySQL的示例项目。
,Article实体类可以如下定义:
@Entity
@Table(name = "articles")
public class Article {
@Id
@GeneratedValue
private Long id;
@Column(name = "title")
private String title;
@Column(name = "content")
private String content;
// getters and setters
}
主要特征有:
使用@Entity
注解声明这是一个实体类
使用@Table
指定数据库表名为articles
id
字段使用@Id
和@GeneratedValue
注解,指定为主键和自动增长
其他字段使用@Column
注解指定数据库列名
为字段提供对应的getter
和setter
方法
当我们运行项目时,Spring Data JPA 会根据此对象对应的表的结构:
CREATE TABLE articles (
id bigint AUTO_INCREMENT,
title VARCHAR(255),
content TEXT,
PRIMARY KEY (id)
)
所以通过在实体类上使用JPA注解,我们就实现了:
JPA在后续进行持久化时,就会根据此对象操作对应的数据库表。
根据需求,ArticleRepository可以如下定义:
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
JpaRepository
类Article
Long
通过继承JpaRepository
,我们即声明了一个操作Article
实体类与数据库表对应的仓库接口。
Spring Data JPA会自动为我们实现该接口,提供如下方法:
save() // 保存实体
findAll() //查询全部
findById() // 根据id查询
...
比如findAll()
方法实现为:
public List<Article> findAll() {
return em.createQuery("from Article").getResultList();
}
所以通过继承JpaRepository
,我们只需要定义接口即可:
在后续ArticleService
中,我们可以通过自动装配的方式使用此仓库:
@Autowired
ArticleRepository articleRepository;
通过调用其方法实现与数据库的交互。
根据需求,ArticleService可以如下定义:
@Service
public class ArticleService {
@Autowired
ArticleRepository articleRepository;
public List<Article> findAll() {
return articleRepository.findAll();
}
// 定义其他方法
}
使用@Service
注解声明这是一个服务类
通过@Autowired
自动装配ArticleRepository
定义findAll()
方法调用仓库的findAll()
方法获取全部文章
可以定义其他业务方法,调用Repository
所以在服务类中:
@Autowired
注入对应的仓库同时我们:
在Controller中,我们可以注入此服务类使用:
@Autowired
ArticleService articleService;
// ...
articleService.findAll();
通过这种设计:
实现了清晰的分层结构。
根据你的需求,ArticleController可以如下定义:
@RestController
@RequestMapping("/api/articles")
public class ArticleController {
@Autowired
ArticleService articleService;
@GetMapping
public List<Article> findAll() {
return articleService.findAll();
}
@GetMapping("/{id}")
public Article findById(@PathVariable Long id) {
...
}
// 其它API
}
主要特征:
使用@RestController
注解,代表一个RESTful的控制器
使用@RequestMapping
指定基础URL为/api/articles
通过@Autowired
注入ArticleService
使用@GetMapping
标注GET
请求路由,映射到方法
在方法中调用服务进行业务逻辑
使用@PathVariable
绑定URL模板变量,如id
返回对应实体类的JSON数据
通过这种方式,我们定义了与Article相关的所有RESTful API:
GET /api/articles
获取全部文章GET /api/articles/{id}
根据id获取文章客户端(前端)通过这些接口与后端交互,获取JSON格式的数据。
根据需求,可以按照以下方式定义Tag、Comment等实体类:
@Entity
public class Tag {
@Id
@GeneratedValue
private Long id;
@Column(name = "name")
private String name;
@ManyToMany
@JoinTable(
name = "article_tag",
joinColumns = @JoinColumn(name = "tag_id"),
inverseJoinColumns = @JoinColumn(name = "article_id"))
private Set<Article> articles;
// getters and setters
}
@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
@Column(name = "content")
private String content;
@ManyToOne
@JoinColumn(name = "article_id")
private Article article;
// getters and setters
}
主要特征:
@ManyToMany
一个标签对应多个文章@ManyToOne
一个评论对应一个文章@JoinTable
指定关系表article_tag
getter
和setter
方法通过这种方式,我们可以:
根据你的需求,可以按以下步骤分别构建和部署Vue前端项目和Spring Boot后端项目:
使用vue create
命令创建Vue项目
安装依赖:npm install
开发前端组件,定义接口调用等
构建产物:
npm run build
此命令会构建出一个dist
文件夹,包含静态文件
dist
文件夹到任意web服务器即可提供服务npm install -g serve
安装serve
,使用serve -s dist
本地部署使用IDE创建Spring Initializr项目
连接MySQL数据库,编写实体、服务、接口等代码
构建产物:
./mvnw package
生成一个可执行的jar
文件
java -jar demo.jar
通过这种方式,我们可以:
实现前后端完全分离的个人博客系统。
前端Vue项目通过Axios调用Spring Boot提供的JSON API的过程如下:
在Vue项目中,需要:
npm install axios
import axios from 'axios'
export default {
getArticles() {
return axios.get('http://localhost:8080/api/articles')
}
}
import ArticleApi from './api/article'
export default {
methods: {
async loadArticles() {
let { data } = await ArticleApi.getArticles()
this.articles = data
}
}
}
created() {
this.loadArticles()
}
在Spring Boot后端,需要定义:
@GetMapping("/api/articles")
public List<Article> getArticles() {
return articleService.findAll();
}
ArticleService,ArticleRepository
在Spring Boot后端,需要定义:
ArticleService
@Service
public class ArticleService {
@Autowired
ArticleRepository articleRepository;
public List<Article> findAll() {
return articleRepository.findAll();
}
}
ArticleService中的方法:
ArticleRepository
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
ArticleRepository:
ArticleController
@RestController
public class ArticleController {
@Autowired
ArticleService articleService;
@GetMapping("/api/articles")
public List<Article> getArticles() {
return articleService.findAll();
}
}
ArticleController:
三者组合结构:
分层设计:
所以在Spring后端,需要定义三个部分:Repository(数据)、Service(业务)和Controller(API)。
上述接口会返回:
[
{
"id": 1,
"title": "Introduction to Spring Boot",
"content": "..."
},
...
]
Vue项目通过Axios调用该接口,获取JSON数据,再设置给articles
用来渲染。
通过这种方式,我们实现了:
通过以上步骤,我们就可以实现一个基于Vue、Spring Boot和MySQL的简单个人博客系统,实现前后端分离
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。