请搭建一个springboot加vue的demo项目
好的,以下是一个简单的Spring Boot + Vue.js的Demo项目搭建步骤:
首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr(https://start.spring.io/)快速创建一个基础项目,选择Maven项目和Spring Boot版本,并添加Web和Thymeleaf依赖。下载生成的项目后,使用IDEA或者其他IDE打开。
接下来,我们需要添加Vue.js到项目中。在项目根目录下新建一个名为“frontend”的文件夹,用于存放前端代码。我们可以使用Vue.js官方提供的脚手架工具Vue CLI来快速创建一个Vue.js项目。
首先,确保已经安装了Node.js和npm。然后在命令行中输入以下命令安装Vue CLI:
npm install -g vue-cli
安装完成后,在frontend目录下执行以下命令创建一个Vue.js项目:
vue init webpack frontend
在执行过程中,需要输入一些基本信息,例如项目名称、描述等。完成后,进入frontend目录,执行以下命令安装项目依赖:
npm install
接下来,我们需要将Vue.js项目与Spring Boot项目集成。在Spring Boot项目的src/main/resources/static目录下新建一个名为“frontend”的软链接,指向frontend目录下的dist目录(在frontend目录下执行npm run build生成):
ln -s ../frontend/dist frontend
修改Spring Boot项目的配置文件,将Spring Boot的Web服务器端口设置为8080,并配置静态资源路径:
server: port: 8080 servlet: context-path: / spring: resources: static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:./frontend/
在Spring Boot项目中,添加一个RESTful接口来返回一些数据。例如,在UserController中添加以下代码:
@RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { List<User> users = new ArrayList<>(); users.add(new User(1, "Tom")); users.add(new User(2, "Jerry")); return users; } }
在frontend目录下,修改src/components/HelloWorld.vue文件,使用axios来调用Spring Boot项目中的RESTful接口:
<template> <div class="hello"> <h1>{{ msg }}</h1> <ul> <li v-for="user in users" :key="user.id">{{ user.name }}</li> </ul> </div> </template> <script> import axios from 'axios' export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App', users: [] } }, mounted () { axios.get('/users').then(response => { this.users = response.data }) } } </script>
最后,在frontend目录下执行以下命令启动Vue.js开发服务器:
npm run dev
在浏览器中访问http://localhost:8081,应该可以看到Vue.js的示例页面,其中包含了从Spring Boot项目中获取到的数据。
至此,一个简单的Spring Boot + Vue.js的Demo项目就搭建完成了。
相关推荐


















