程序员开发实例大全宝库

网站首页 > 编程文章 正文

在SpringBoot项目中开发前端页面(springboot 前台)

zazugpt 2024-09-11 11:31:02 编程文章 20 ℃ 0 评论

当前的Web开发一般都是前后端分离的,但是对一些小型项目来说,做前后端分离反而会影响开发的效率,对小项目来说,前后端放在一起开发反而是更合适的。

如何在SpringBoot项目中开发前端页面呢?我们一起来看看。

创建html页面

在SpringBoot项目中,有一个目录是专门用来存放前端代码的:src/main/resources/static。

我们现在这个目录中创建一个html文件:user.html

使用Vue展示动态数据

为了将后端查询的动态数据展示在浏览器页面上,需要动态加载数据,Vue是当前最流行的前端框架,我使用它来动态加载和展示数据。

为了减少复杂度,我们直接使用CDN的方式加载Vue库,在<head>标签内加入如下代码:

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

使用js初始化Vue对象,并设置数据对象。

data方法内的返回值userId和username是我们需要从后端获取的数据,先定义好变量。

    const {createApp } = Vue
    createApp({
        data() {
            return {
                userId:'',
                userName:''
            }
        }
    }).mount('#app')

使用Vue的文本插值语法(双大括号)在页面上进行数据展示。

<h1>用户信息</h1>
<div id="app">
    用户id:{{userId}}
    用户名称:{{userName}}
</div>

使用axios获取后端数据

通过axios发送异步请求获取后端数据。

使用CDN加载axios库。

<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>

created方法是Vue的钩子函数,在页面创建完成后调用,查询后端数据的方法可以在这个函数里进行调用。

我们在created方法中使用axios调用后端接口获取数据。axios返回的数据结构中,自动加了data属性,用于存储后端返回的数据。在开发的后端接口中也定义了R类,规范了返回数据的格式,所以此处有两层data。

created(){
            axios.get("/user/1").then((res)=>{
                console.log(res.data.data)
                this.userId = res.data.data.userId
                this.userName = res.data.data.username
            })
}

启动测试

启动SpringBoot应用,在浏览器中输入访问地址:http://localhost:8080/user.html

正确访问到了刚才创建的前端页面,也动态加载了数据。

完整的前端代码

完整的user.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
    <script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<h1>用户信息</h1>
<div id="app">
    用户id:{{userId}}
    用户名称:{{userName}}

</div>
</body>

<script>
    const {createApp } = Vue
    createApp({
        data() {
            return {
                userId:'',
                userName:''
            }
        },
        created(){
            axios.get("/user/1").then((res)=>{
                console.log(res.data.data)
                this.userId = res.data.data.userId
                this.userName = res.data.data.username
            })
        }
    }).mount('#app')

</script>
</html>

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表