12-SpringBoot用户列表渲染案例
文章目录
- 1 文章介绍
- 2 创建一个SpringBoot工程,并勾选web依赖、lombok。
- 2.1 报错提示
- 3.引入资料中准备好的用户数据文件(user.txt),及前端静态页面
- 3.1 拷贝粘贴前端静态资源
- 4 定义一个实体类,用来封装用户信息
- 5 开发服务端程序,接收请求,读取文本数据并响应
- 6 启动服务测试,访问:[http://localhost:8080/user.html](http://localhost:8080/user.html)
- 7 项目小结
1 文章介绍
项目需求
视频详解https://www.bilibili.com/video/BV1yGydYEE3H/?p=46&spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=7d4af6875c8641b756bb3d4317f287f0
2 创建一个SpringBoot工程,并勾选web依赖、lombok。
运行空项目,出现spring图片即项目创建成功
2.1 报错提示
报错1:Lombok requires annotation processing to be enabled
翻译:需要开启注解处理器(Annotation Processing),否则 IDEA 编译时不会识别 @Data、@Getter、@Setter 等注解。 processing to be enabled()
3.引入资料中准备好的用户数据文件(user.txt),及前端静态页面
3.1 拷贝粘贴前端静态资源
粘贴后效果图
4 定义一个实体类,用来封装用户信息
在com,itheima包中新建pojo包和用户类,结构如下
5 开发服务端程序,接收请求,读取文本数据并响应
请求处理类UserController完整代码
package com.itheima.controller;import cn.hutool.core.io.IoUtil;
import com.itheima.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.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;@RestController
public class UserController {@RequestMapping("/list")public List<User> list(){//1.加载并读取文件InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());//2.解析数据,封装成对象 --> 集合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);}).collect(Collectors.toList());//3.响应数据//return JSONUtil.toJsonStr(userList, JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss"));return userList;}}
新增依赖包----Hutool 工具包
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.27</version></dependency>
6 启动服务测试,访问:http://localhost:8080/user.html
出现用户列表数据,则该web程序成功