I am currently utilizing thymeleaf as my chosen template engine for a spring boot project.
Here is the directory structure:
src/main/
|- java
| - UserAdministrationController.java
|- resources
| - static
| - admin
| - css
| - template.css
| - js
| - template.js
| - templates
|- incs
|- inc_form_create_user.html
|- users.html
The controller is annotated with:
@Controller
@RequestMapping("/administration/users")
There is a method to retrieve the users page:
@RequestMapping("")
public ModelAndView getUsersPage() {
return new ModelAndView("admin/users");
}
Another method handles user creation:
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String handleUserCreateForm(@Valid @ModelAttribute("form") UserDTO form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return getUsersPage().getViewName();
}
try {
userService.create(form);
} catch (DataIntegrityViolationException e) {
bindingResult.reject("email.exists", "Email already exists");
return getUsersPage().getViewName();
}
return "redirect:/administration/users";
}
Finally, there is a method that adds a user model when called to fill out a form:
@RequestMapping("/{id}/edit")
public ModelAndView getEditPage(@PathVariable("id") long id) {
ModelAndView model = new ModelAndView("admin/users");
model.addObject("userToEdit", userService.getUserById(id));
return model;
}
Including both create and edit forms on the same page using conditional includes:
<div th:if="${userToEdit == null}" class="panel panel-default" th:include="admin/incs/inc_form_create_user :: createUserForm" ></div>
<div th:if="${userToEdit != null}" class="panel panel-default" th:include="admin/incs/inc_form_create_user :: editUserForm" ></div>
Importing CSS files in the HTML:
<link th:href="@{../../admin/css/template.css}" rel="stylesheet" />
Accessing user.html and encountering an issue when calling the edit method with a different URI:
URL for creating a user:
http://localhost:8080/administration/users
URL for editing a user:
http://localhost:8080/administration/users/10/edit
Both cases importing the CSS file:
../../admin/css/template.css
However, in the edit case, the browser console displays this error message:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/administration/admin/css/template.css