EventCategory
Class¶First, create a new class called EventCategory
in the models
directory.
EventCategory
needs to have the following:
id
field of type int
.name
field of type String
.EventCategory
represents data that will be stored in our database, so you need to use the @Entity
annotation!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | @Entity
public class EventCategory {
@Id
@GeneratedValue
private int id;
@Size(min=3, message="Name must be at least 3 characters long")
private String name;
public EventCategory(@Size(min = 3, message = "Name must be at least 3 characters long") String name) {
this.name = name;
}
public EventCategory() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventCategory that = (EventCategory) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
EventCategoryController
Class¶displayAllEvents
¶displayAllEvents
needs to do the following:
@GetMapping
and return "eventCategories/index"
.title
that uses "All Categories"
.categories
that uses all of the values in your EventCategoryRepository
variable.1 2 3 4 5 6 | @GetMapping
public String displayAllCategories(Model model) {
model.addAttribute("title", "All Categories");
model.addAttribute("categories", eventCategoryRepository.findAll());
return "eventCategories/index";
}
|
processCreateEventCategoryForm
¶processCreateEventCategoryForm
needs to do the following:
@PostMapping
.Errors
object appropriately. If you want to review how to use the Errors
object, check out the section on error validation.title
and assign it "Create Category"
.EventCategory
."eventCategories/create"
or "redirect:"
.1 2 3 4 5 6 7 8 9 10 11 12 | @PostMapping("create")
public String processCreateEventCategoryForm(@Valid @ModelAttribute EventCategory eventCategory, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Category");
model.addAttribute(new EventCategory());
return "eventCategories/create";
}
eventCategoryRepository.save(eventCategory);
return "redirect:";
}
|
To finish the exercises, we need to make two new templates.
eventCategories/index
, which will contain a table of the event categories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head th:replace="fragments :: head"></head>
<body class="container">
<header th:replace="fragments :: header"></header>
<table class="table table-striped">
<thead>
<tr>
<th>Category Name</th>
</tr>
</thead>
<tr th:each="category : ${categories}">
<td th:text="${category.name}"></td>
</tr>
</table>
</body>
</html>
|