SpringBoot后端基础案例

文章目录

需求说明

基于SpringBoot开发web程序,完成用户列表的渲染展示。当在浏览器地址栏,访问前端静态页面(http://localhost:8080/usre.html)后,在前端页面上,会发送ajax请求,请求服务端(http://localhost:8080/list),服务端程序加载 user.txt 文件中的数据,读取出来后最终给前端页面响应json格式的数据,前端页面再将数据渲染展示在表格中。

代码实现

  1. 创建一个SpringBoot工程

  2. 将user.txt放在resources下

    1,daqiao,1234567890,大乔,22,2024-07-15 15:05:45
    2,xiaoqiao,1234567890,小乔,18,2024-07-15 15:12:09
    3,diaochan,1234567890,貂蝉,21,2024-07-15 15:07:16
    4,lvbu,1234567890,吕布,28,2024-07-16 10:05:15
    5,zhaoyun,1234567890,赵云,27,2024-07-16 11:03:28
    6,zhangfei,1234567890,张飞,31,2024-07-16 11:03:28
    7,guanyu,1234567890,关羽,34,2024-07-16 12:05:12
    8,liubei,1234567890,刘备,37,2024-07-16 15:03:28

  3. 将js和html放在static下

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表数据</title>
    <style>
        /*定义css,美化表格*/
        table{
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
            border: 1px solid #ccc;
            text-align: center;
            font-size: 14px;
        }
        tr {
            height: 40px;
        }
        th,td{
            border: 1px solid #ccc;
        }
        thead{
            background-color: #e8e8e8;
        }
        h1{
            text-align: center;
            font-family: 楷体;
        }
    </style>
</head>
<body>
    <div id="app">
        <h1>用户列表数据</h1>
        <!--定义一个表格,包括6列,分别是: ID, 用户名, 密码, 姓名, 年龄, 更新时间-->
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>更新时间</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in userList">
                    <td>{{user.id}}</td>
                    <td>{{user.username}}</td>
                    <td>{{user.password}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.age}}</td>
                    <td>{{user.updateTime}}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <!--引入axios-->
    <script src="js/axios.min.js"></script>
    <script type="module">
        import { createApp } from './js/vue.esm-browser.js'
        createApp({
            data() {
                return {
                    userList: []
                }
            },
            methods: {
                async search(){
                    const result = await axios.get('/list');
                    this.userList = result.data;
                }
            },
            mounted() {
                this.search();
            }
        }).mount('#app')
    </script>
</body>
</html>
  1. 定义封装用户信息的实体类
    这里使用lombok一直报错,所以自己写了getter和setter
java 复制代码
package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * 封装用户信息
 */
@Data // 生成全参构造器
//@AllArgsConstructor
//@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Integer age;
    private LocalDateTime updateTime;

    // 无参构造器(Spring 框架需要)
    public User() {}

    // 新增6参数构造器
    public User(Integer id, String username, String password,
                String name, Integer age, LocalDateTime updateTime) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.name = name;
        this.age = age;
        this.updateTime = updateTime;
    }

    // Getter/Setter 方法
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

}
  1. pom.xml中引入依赖
java 复制代码
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.27</version>
</dependency>
  1. 创建一个UserController,用来获取user.txt中的字符串,解析用户信息并封装,最后返回json格式的数据(返回List即可返回json格式的数据)
java 复制代码
package com.example.controller;

import cn.hutool.core.io.IoUtil;
import com.example.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息controller
 */
@RestController
public class UserController {
    @RequestMapping("/list")
    public List<User> list() throws Exception{
        //加载并读取user.txt
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");
        ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());

        //解析用户信息,封装
        List<User> userList = lines.stream().map(line -> {
            String[] parts = line.split(",");
            Integer id = Integer.parseInt(parts[0]);
            String username = parts[1];
            String password = parts[2];
            String name = parts[3];
            Integer age = Integer.parseInt(parts[4]);
            LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return new User(id, username, password, name, age, updateTime);
        }).toList();

        //返回json数据
        return userList;
    }
}

运行结果

代码目录

运行并访问

相关推荐
Terio_my3 分钟前
Java bean 数据校验
java·开发语言·python
Tony Bai7 分钟前
【Go开发者的数据库设计之道】07 诊断篇:SQL 性能诊断与问题排查
开发语言·数据库·后端·sql·golang
超级大只老咪29 分钟前
何为“类”?(Java基础语法)
java·开发语言·前端
花花鱼1 小时前
spring boot项目使用tomcat发布,也可以使用Undertow(理论)
spring boot·后端·tomcat
我笑了OvO1 小时前
C++类和对象(1)
java·开发语言·c++·类和对象
weixin_436525072 小时前
Gitee - IDEA 主支 master 和分支 dev 的使用
java·ide·intellij-idea
你的人类朋友3 小时前
快速搭建redis环境并使用redis客户端进行连接测试
前端·redis·后端
sheji34163 小时前
【开题答辩全过程】以 YF精品视频动漫平台为例,包含答辩的问题和答案
java·eclipse
小蕾Java3 小时前
Java 开发工具,最新2025 IDEA 使用
java·ide·intellij-idea
是席木木啊3 小时前
Idea升级到2024版本:“marketplace plugins are not loaded”解决方案
java·ide·intellij-idea