03 Model-View-Controller
Controller
The controller is responsible for handling requests and generating responses.
Spring Controller
The spring controller is a Java class annotated with @Controller and @RequestMapping (to map it to the correct url).
Full documentation on the controller can be found here.
@Controller
@RequestMapping(value = "/questionnaires")
public class QuestionnaireController {
@Autowired // Dependency Injection
private QuestionnaireRepository questionnaireRepository;
@GetMapping // Map to GET requests
public String findAll(Model model) {
List<Questionnaire> questionnaires = questionnaireRepository.findAll();
model.addAttribute("questionnaires", questionnaires);
return "questionnaires/list";
}
@GetMapping(value = "/{id}") // Map to GET requests with a path variable
public String findById(@PathVariable String id, Model model) {
Optional<Questionnaire> questionnaire = questionnaireRepository.findById(id);
if (questionnaire.isEmpty()) {
return "404";
}
model.addAttribute("questionnaire", questionnaire.get());
return "questionnaires/show";
}
}
Model
The model is responsible for managing the data and the business logic. It is independent of the user interface.
Spring Model
The model is used to pass data to the view. It is passed as a parameter to the controller method.
Data is added with the addAttribute or mergeAttributes.
Full documentation on the model can be found here.
@GetMapping(params = {"form"})
public String getForm(Model model) {
model.addAttribute("questionnaire", new Questionnaire()); // Add a new questionnaire to the model
return "questionnaires/create";
}
@GetMapping(value = "/{id}", params = {"update-form"})
public String getUpdateForm(@PathVariable String id, Model model) {
Optional<Questionnaire> questionnaire = questionnaireRepository.findById(id);
if (questionnaire.isEmpty()) {
return "404";
}
model.addAttribute("questionnaire", questionnaire.get()); // Add the questionnaire to the model
return "questionnaires/update";
}
View
The view is responsible for displaying the data to the user and receive input from the user and forward it to the controller. It is the only component which is visible to the user.
Spring uses the ThymeLeaf template engine to render HTML pages.
ThymeLeaf
Views are returned by the controller as a string. The string is the name of the HTML file without the extension or a redirect.
For example, if the templates folder structure looks like the following:
resources/
└── templates/
├── questionnaires/
│ ├── create.html
│ ├── list.html
│ ├── show.html
│ └── update.html
├── 404.html
├── error.html
├── footer.html
├── header.html
└── layout.html
return "404"would return the404.htmlfile.return "questionnaires/create"would return thecreate.htmlfile in thequestionnairesfolder.return "redirect:/questionnaires"would redirect to the/questionnairesweb page.
The ThyemeLeaf template engine documentation can be found here.