1、springboot+vue前后端不分离的项目,前端怎么与后端进行交互的,前端如何向后端发送请求(如何调用后端接口)

前后端不分离项目常用Ajax、Axios或者Vue-resource请求接口; 对需要实时通讯的则可以考虑SockJS或WebSocket等技术。

(1)原生Ajax请求

前端使用XMLHttpRequest或者Fetch API发送Ajax请求到后端,调用后端restful接口。( fetch API可以替代传统的XMLHttpRequest对象来进行网络请求。)

1
2
3
4
5
6
7
8
// Vue组件方法
getData() {
fetch('/api/users')
.then(response => response.json())
.then(data => {
// 使用数据
})
}

(2)Axios

Axios是非常流行的ajax请求库,使用起来比原生的更简单。

1
2
3
4
5
6
7
8
9
10
11
12
13
// Vue组件
import axios from 'axios'

export default {
methods: {
getData() {
axios.get('/api/users')
.then(response => {
// 使用数据
})
}
}
}

(3)Vue-resource

Vue-resource是一个官方不再维护的库,但可以方便地发送ajax请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Vue组件
import VueResource from 'vue-resource'

export default {
// 注册插件
plugins: [VueResource],

methods: {
getData() {
this.$http.get('/api/users')
.then(response => {
// 使用数据
})
}
}
}

(4)SockJS

利用Socket技术实现长连接实时通信,保持前后端心跳连接。

(5)WebSocket

支持原生WebSocket协议实现双向实时通信。

(6)EventBus

通过全局事件总线机制交互,针对不需要实时的情况。

2、controller层并没有显式设置“/”的路径,为什么启动后localhost:8080地址会自动显示index.html页面的内容

1、您使用的Spring Boot版本内置了默认首页处理规则。

从Spring Boot 2.0版本开始,它默认会从项目类路径下的静态资源文件夹(如src/main/resources/static)查找首页文件index.html,并直接返回。

2、所以尽管您的Controller代码没有设置”/“路径,但Spring Boot会自动从静态资源文件夹查找并返回index.html。

3、可以这么理解:

  • 当请求”/“时,Spring MVC试图找一个Controller处理
  • 找不到时,Spring Boot自动从静态资源文件夹(如/static)寻找index.html文件
  • 返回index.html内容给浏览器

4、若不需要这个默认规则,可以配置自己的首页路径,如设为欢迎页:

1
2
3
4
5
6
7
8
9
@Bean
public WebMvcConfigurer configurer(){
return new WebMvcConfigurerAdapter(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/welcome");
}
};
}

所以,总之是Spring Boot默认的静态资源处理规则,让”/“能自动找到index.html而返回。

Spring Boot项目能自动跳转到index.html页面,主要原因有以下几点:

  1. Spring Boot默认会寻找静态资源,index.html就被视为默认的首页。
  2. Spring Boot在类路径下的静态资源文件夹中寻找静态资源文件,默认位置为:
  • src/main/resources/static
  • src/main/resources/public
  • src/main/resources/resources/static
  • src/main/resources/resources/public
  1. 通常我们会把index.html等前端文件放在src/main/resources/static目录下。

  2. 在这种情况下,当请求URL为项目根路径”/“时,Spring Boot会自动寻找static目录下的index.html来作为首页响应。

  3. 也可以自己配置欢迎页,例如在WebMvcConfigurer中设置默认的首页。

3、有没有Springboot+vue+thymeleaf项目(这种情况前后端可不可以分离分离)?

有,可以使用前后端不分离的。

https://www.cnblogs.com/1399z3blog/p/15788700.html