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;
    }
}

运行结果

代码目录

运行并访问

相关推荐
哈基米喜欢哈哈哈3 小时前
ThreadLocal 内存泄露风险解析
java·jvm·面试
萌新小码农‍3 小时前
Java分页 Element—UI
java·开发语言·ui
鼠鼠我捏,要死了捏3 小时前
深入实践G1垃圾收集器调优:Java应用性能优化实战指南
java·g1·gc调优
书院门前细致的苹果3 小时前
ArrayList、LinkedList、Vector 的区别与底层实现
java
再睡亿分钟!3 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring
qq_195551694 小时前
代码随想录70期day7
java·开发语言
Sam-August4 小时前
【分布式架构实战】Spring Cloud 与 Dubbo 深度对比:从架构到实战,谁才是微服务的王者?
java·spring cloud·dubbo
麦兜*4 小时前
MongoDB 常见错误解决方案:从连接失败到主从同步问题
java·数据库·spring boot·redis·mongodb·容器
ytadpole5 小时前
揭秘设计模式:命令模式-告别混乱,打造优雅可扩展的代码
java·设计模式