2021年1月22日 星期五

[SpringBoot 1.5] SpringBoot 查詢範例

當我們要將員工資訊顯示出來

這就是一個查詢功能







我們的model為一個Employee類別 屬性如下

public class Employee {

private Integer id;
private String lastName;

private String email;
//1 male, 0 female
private Integer gender;
private Department department;
private Date birth;

然後我們設置一個controller中的方法

@Repository
public class EmployeeDao {
@GetMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();

model.addAttribute("emps",employees);
return "emp/list";
}

我們使用model.addAttribute來設置model中內容

當他點選到該連結, 就可以導向過來controller再return給list頁面

<a class="nav-link active"
th:class="${activeUri=='emps.html'?'nav-link active':'nav-link'}"
href="#" th:href="@{/emps}">

其中搭配著employeeDao為

@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;

@Autowired
private DepartmentDao departmentDao;

static{
employees = new HashMap<Integer, Employee>();

employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
}

private static Integer initId = 1006;


public Collection<Employee> getAll(){
return employees.values();
}
}

而前端的頁面為

<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender} == 0 ? '' : ''"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm:ss')}"></td>
<td>
<!--<a th:href="@{/emp/} + ${emp.id}" class="btn btn-sm btn-primary">编辑</a>-->
<a th:href="@{/emp/} + ${emp.id}" class="btn btn-sm btn-primary">编辑</a>
<button th:attr="del_uri = @{/emp/} + ${emp.id}" type="submit" class="btn btn-sm btn-danger deleteBtn">删除</button>
</td>
</tr>

為一個使用th:each來遍歷model中emps的每一筆資料, 時間格是可以用dates.format

查出每筆資料有兩種寫法, 一種為th:text="${model.attribute}"

另外一種為[[${model.attribute}]]


沒有留言:

張貼留言

[leetcode] [KMP] KMP

ABCDABD... ABCDABF... 簡單的說, 傳統解兩字串匹配部分 可能會來個雙迴圈, 哀個比對, 當不匹配的時候, 會將下方列再後移1位 然後不匹配再後移 然而 如果像上放已經有4個屬於匹配的字串, 她就應該直接往後移四位來匹配, 而不是只移動1位 隱藏的思維是, 當...