使用 thymeleaf 获取用户列表

1,新建ThymeleafContorllor类


package com.xiang.controller;

import com.xiang.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/xiang")
public class ThymeleafContorllor {

    @GetMapping("/user/userList")
    public  String userList(Model model){
        List<User> list = new ArrayList<>();


        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            User user = new User();
            user.setId(001);
            user.setName("小向");
            user.setBirthday(format.parse("2000-06-23"));
            list.add(user);

            user = new User();
            user.setId(002);
            user.setName("小小");
            user.setBirthday(format.parse("2021-11-11"));
            list.add(user);

            user = new User();
            user.setId(003);
            user.setName("小小");
            user.setBirthday(format.parse("2021-11-11"));
            list.add(user);

            user = new User();
            user.setId(004);
            user.setName("小小");
            user.setBirthday(format.parse("2021-11-11"));
            list.add(user);


            model.addAttribute("users",list);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "userList";
    }

}

2,新建model包下新建User类

package com.xiang.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
//包含:id, name, birthday(日期), salary(浮点类型 工资)等字段
    private Integer id;
    private  String name;
    @DateTimeFormat(pattern ="yyyy-MM-dd")
    private Date birthday;
    private  Double salary;
}

3,在resources 下的 templates目录下编写前端代码 文件名为:userList.html


<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>userList</title>
</head>
<body>


<h3>用户列表</h3>
<table border="1">
  <tr>
    <th>编号</th>
    <th>姓名</th>
    <th>生日(美国时间)</th>
    <th>生日(中国时间)</th>
  </tr>
  <tr th:each="user:${users}">
    <td th:text="${user.id}"></td>
    <td th:text="${user.name}"></td>
    <td th:text="${user.birthday}"></td>
    <td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd mm:HH')}"></td>

  </tr>
</table>


</body>
</html>

3,运行结果截图

原文地址:https://www.cnblogs.com/d534/p/14889685.html