Tutorial 5
Tutorial 5
Contents:
Build data filter for web app with Spring Boot, Thymeleaf & JavaScript
Instructions:
1. Import the previous project of Tutorial 4 to continue coding.
2. In your getAllEmployee() method, add a list of all companies into the model object:
List<Company> companies = companyRepository.findAll();
model.addAttribute("companies", companies);
SE2 – TUTORIAL 5
You’ll be able to receive querystring parameters in this controller method. For example:
http://localhost:8080/employee/list?company=1&sort=2
5. Add these values to the model object so that we can use them later in the Thymeleaf
template:
model.addAttribute("comId", comId);
model.addAttribute("sortMode", sortMode);
6. Use JavaScript to redirect to the correct web URL when a filter changes its value.
Also use JavaScript to make sure the selected value on the drop-down menus
reflect the current filter choices:
<script>
let comId = [[${ comId }]];
let sortMode = [[${ sortMode }]];
function filterRedirect() {
let url = "/employee/list?company=" + comId + "&sort=" + sortMode;
window.location.href = url; // redirect
}
window.addEventListener("load", function () {
const comFilter = document.getElementById("filterCompany");
comFilter.value = comId;
comFilter.addEventListener("change", function (e) {
comId = e.target.value;
filterRedirect();
});
const sortMenu = document.getElementById("sortOptions");
sortMenu.value = sortMode;
sortMenu.addEventListener("change", function (e) {
sortMode = e.target.value;
filterRedirect();
});
});
</script>
(*) Teacher should explain the above JavaScript code for you in case you’re not proficient
in JS programming.
SE2 – TUTORIAL 5
7. Add a query method in EmployeeRepository to get employees by company and
also apply sorting to the result:
if (sortMode == 1 || sortMode == 2) {
sortOrder = Sort.Direction.ASC;
}
if (sortMode == 2 || sortMode == 3) {
sortColumn = "name";
}
9. Try to get the list of employees from a specific company (don’t forget to check if that
company exists first):
Please note that, if the provided company is not found, this will results in the employees
object still being null.
10. If the list of employees from a company was not retrieved, we will get a list of
employees from all companies:
if (employees == null) {
// failed to filter by Company
employees = employeeRepository.findAll(
Sort.by(sortOrder, sortColumn)
);
}
SE2 – TUTORIAL 5
Run, debug & submit your project
Once finished, compress your project into a .zip file and submit the file to the tutorial’s
submission box.
SE2 – TUTORIAL 5