SpringBootWeb案例附带源代码
核心代码如下:
- package com.zidiu.controller;
-
- import cn.hutool.core.io.IoUtil;
- import com.zidiu.pojo.User;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.io.IOException;
- 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);
- }).toList();
-
- //3.响应数据,返回JSON / 对象或者集合自动转换成json响应给前端
- //return JSONUtil.toJsonStr(userList, JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss"));
- return userList;
- }
- }
复制代码 完整源代码:
demo02.zip
(23.14 KB, 下载次数: 0, 售价: 10 金币)
|