国庆节10月1日
--


基于SpringBoot开发Web程序完成用户列表渲染的完整案例
本案例展示了如何使用SpringBoot开发一个Web应用,完成用户列表的渲染展示。前端页面通过Ajax请求后端接口,后端从文本文件中加载用户数据并返回JSON格式数据,前端再将数据渲染展示在表格中。
1package com.itheima.pojo;2
3import lombok.AllArgsConstructor;4import lombok.Data;5import lombok.NoArgsConstructor;6import java.time.LocalDateTime;7
8@Data9@NoArgsConstructor10@AllArgsConstructor11public class User {12 private Integer id;13 private String username;14 private String password;15 private String name;16 private Integer age;17 private LocalDateTime updateTime;18}1<dependency>2 <groupId>cn.hutool</groupId>3 <artifactId>hutool-all</artifactId>4 <version>5.8.27</version>5</dependency>1import cn.hutool.core.io.IoUtil;2import cn.hutool.json.JSONConfig;3import cn.hutool.json.JSONUtil;4import com.itheima.pojo.User;5import org.springframework.web.bind.annotation.RequestMapping;6import org.springframework.web.bind.annotation.RestController;7import java.io.InputStream;8import java.nio.charset.StandardCharsets;9import java.time.LocalDateTime;10import java.time.format.DateTimeFormatter;11import java.util.ArrayList;12import java.util.List;13import java.util.stream.Collectors;14
15@RestController16public class UserController {17 @RequestMapping("/list")18 public String list(){19 //1.加载并读取文件20 InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");21 ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());22 //2.解析数据,封装成User对象23 List<User> userList = lines.stream().map(line -> {24 String[] parts = line.split(",");25 return new User(26 Integer.parseInt(parts[0]), parts[1], parts[2],27 parts[3], Integer.parseInt(parts[4]),28 LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))29 );30 }).collect(Collectors.toList());31 //3.响应JSON数据32 return JSONUtil.toJsonStr(userList, JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss"));33 }34}@RestController = @Controller + @ResponseBody,在类上加此注解后,所有方法自动带有@ResponseBody功能@RestController注解,无需在方法上加@ResponseBody如果你喜欢,那么欢迎来到我的世界!
了解更多暂未播放



"所有的相遇都是久别重逢。"—— 未知


