知识杂货铺 知识杂货铺
首页
后端(1本书)
  • 主题初衷与诞生
  • 介绍
  • 快速上手
  • 目录结构
  • 核心配置和约定
  • 自动生成front matter
  • Markdown 容器
  • Markdown 中使用组件
  • 相关文章

    • 使目录栏支持h2~h6标题
    • 如何让你的笔记更有表现力
    • 批量操作front matter工具
    • 部署
    • 关于写文章和H1标题
    • 关于博客搭建与管理
    • 在线编辑和新增文章的方法
  • 主题配置
  • 首页配置
  • front matter配置
  • 目录页配置
  • 添加摘要
  • 修改主题颜色和样式
  • 评论栏
  • 快速开始
  • 代码集成_TODO
  • 框架初探
  • 在GitHub上贡献代码
  • 使用K8s部署系统
  • Seata分布式事务
GitHub (opens new window)

Kevin Zhang

爱凑热闹的高龄程序猿
首页
后端(1本书)
  • 主题初衷与诞生
  • 介绍
  • 快速上手
  • 目录结构
  • 核心配置和约定
  • 自动生成front matter
  • Markdown 容器
  • Markdown 中使用组件
  • 相关文章

    • 使目录栏支持h2~h6标题
    • 如何让你的笔记更有表现力
    • 批量操作front matter工具
    • 部署
    • 关于写文章和H1标题
    • 关于博客搭建与管理
    • 在线编辑和新增文章的方法
  • 主题配置
  • 首页配置
  • front matter配置
  • 目录页配置
  • 添加摘要
  • 修改主题颜色和样式
  • 评论栏
  • 快速开始
  • 代码集成_TODO
  • 框架初探
  • 在GitHub上贡献代码
  • 使用K8s部署系统
  • Seata分布式事务
GitHub (opens new window)
  • Spring Boot 培训教程
  • Spring Boot介绍

  • 开发环境配置

  • 原理剖析

  • Web开发

  • 数据访问

  • 事务

  • 集成Redis

  • 集成MongoDB

  • 异步消息

  • 异常处理

  • 单元测试与热部署

  • 安全控制

  • 应用监控

  • 企业级开发

  • 多环境配置与部署

  • 综合示例

  • 前后端分离的vue急速入门

    • Vue快速入门
    • Vue简介
    • 开发环境配置
    • 最简前后端分离项目
      • A1.3 Hello Vue
    • 路由示例
    • 应用部署
    • 06小结
    • 课后作业
  • Spring Boot配置大全

  • 在Docker中部署Spring Boot应用

  • 开发前后端分离应用

  • 前进到Spring Cloud

  • 规则引擎

  • 流程引擎

  • 后记
  • 后端
  • 前后端分离的vue急速入门
Kevin Zhang
2024-10-30
目录

最简前后端分离项目

# A1.3 Hello Vue

本小节使用 vue + Spring Boot 演示一个前后端分离的场景下读取和展示信息的项目,是使用 vue 前后端分离的“Hello World.”。

本示例使用的后台代码如下,其中需要关注的是@CrossOrigin(origins = "*")这个注解,它注解了这个方法(sayHello)是支持跨域访问的。

package com.example.hello.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SayHelloController {
	@Value("${net.xprogrammer.author}")
	private String author;
	
	@Value("${net.xprogrammer.book}")
	private String book;
	
	@RequestMapping("/hello")
	@CrossOrigin(origins = "*")
	public String sayHello() {
		return "Hello Spring Boot. Author=" + author + ", Book=" + book;
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

上面给出的后台代码访问返回的数据情况如下:

image-20191130195936780

首先,在 tomcat 的 ROOT 应用下直接建立一个 hello.html,方便我们测试。

例如,这个路径:C:\Java\apache-tomcat-8.5.47\webapps\ROOT\hello.html,非常简单粗暴。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello Vue</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <div id="app">
    <p>最简单的前后端分离应用:访问后台Spring Boot服务,返回一个字符串消息显示在下面。</p>
    <p><button v-on:click="sayHello">访问后台</button></p>
    <p><h1>{{ helloSpringBoot }}</h1></p>
  </div>

  <script>
    var app = new Vue({
      el: '#app',
      data: {
        helloSpringBoot: '请点击“访问后台”按钮。'
      },
      methods: {
          sayHello() {
            var vm = this;
            axios({
              method: 'get',
              url: 'http://localhost:8080/hello',
            }).then(function (res) {
              vm.helloSpringBoot = res.data;
            }).catch(function (error) {
              console.log(error);
            });
          }          
      }
    })
  </script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  • 在创建的 hello.html 文件内,引入 vue.js,此处采用 CDN 方式直接引入 vue.js 。当引入 vue.js 后,会声明一个 Vue 全局变量,通过 new Vue() 的方式可以获得一个 vue 应用。
  • vue.js 没有集成 ajax 功能,要使用 ajax 功能,可以使用 vue 官方推荐的 axios.js 库来做 ajax 的交互,这个示例中我们也通过 CDN 引入 axios。
  • 在页面声明一个 id="app" 的 div 标签,在 div 内部使用 vue 常见的文本插值方式插入一个 helloSpringBoot 变量。
  • 使用 ID 选择器将 #app 赋给 Vue 的选项的 el 属性,即绑定 vue 视图。
  • 在 vue 内部的 data 部分,定义 helloSpringBoot 并为其赋一个初始值请点击“访问后台”按钮。。
  • 添加一个按钮,绑定到 sayHello 方法。
  • 在 sayHello 方法内访问后台服务(http://localhost:8080/hello), 将返回的数据赋给 helloSpringBoot 变量(vm.helloSpringBoot = res.data;)。
  • vue 自行处理更新页面上的数据。

访问 Tomcat 的 hello.html 页面,显示的是页面及 vue 初始化后的效果,其中 helloSpringBoot 显示的是初始值。

image-20191130195850542

点击“访问后台”按钮后,页面通过 axios 发起 ajax 请求后台服务,获取数据,并显示,效果如下:

image-20191130195821360

补充内容:跨域

跨域问题的产生是出于浏览器的同源策略限制。

同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的 javascript 脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)。

当前页面url 被请求页面url 是否跨域 原因
http://www.test.com/ http://www.test.com/index.html 否 同源(协议、域名、端口号相同)
http://www.test.com/ https://www.test.com/index.html 是 协议不同(http/https)
http://www.test.com/ http://www.baidu.com/ 是 主域名不同(test/baidu)
http://www.test.com/ http://blog.test.com/ 是 子域名不同(www/blog)
http://www.test.com:8080/ http://www.test.com:7001/ 是 端口号不同(8080/7001)

跨域请求的时候,客户端会自动发起一个 OPTIONS 方法到服务器,客户端发起的这个 OPTIONS 可以说是一个“预请求”,用于探测后续真正需要发起的跨域请求对于服务器来说是否是安全可接受的。

请求头 Access-Control-Request-Method 用于提醒服务器在接下来的请求中将会使用什么样的方法来发起请求:

  • Access-Control-Allow-Method 和 Access-Control-Allow-Origin 分别告知客户端,服务器允许客户端用于跨域的方法和域名。

  • 当你的请求地址和浏览器上的 url 地址不一样的时候,由于同源策略,将请求不到资源,将无法“跨域”获取资源。ajax,vue 中的 axios 都会出现跨域问题。

Spring 后台支持 CORS 跨域的办法有如下 3 种:

  1. 通过配置类,为整个应用提供 CORS 跨域支持。
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
  1. 控制器或控制器方法提供 CORS 跨域支持。
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin(origins = "http://domain2.com")
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  1. 基于过滤器的 CORS 跨域支持。
@Configuration
public class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

本小节示例项目代码:

https://github.com/gyzhang/SpringBootCourseCode/tree/master/spring-boot-vue (opens new window)

编辑 (opens new window)
上次更新: 2024/11/17, 16:29:23
开发环境配置
路由示例

← 开发环境配置 路由示例→

最近更新
01
PNG图片处理C++
02-07
02
PNG图片处理
01-24
03
离线安装Docker
12-24
更多文章>
Theme by Vdoing | Copyright © 2008-2025 Kevin Zhang | MIT License | 蜀ICP备20013663号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式