This is the second post in a series of posts to cover different aspects of Spring Boot. Please note that the entire post isn’t necessarily only written in English.
In this post, I am going to cover the basics of Spring Web MVC.
Web MVC
How to display model data & process form input
Template view:
JSP pages (
main/WEB-INF
)Thymeleaf (
main/resources/templates
)
Disable template cache:
spring.thymeleaf.cache = false
(add this toapplication.properties
) (Remember to set back to
True
in production)Use DevTools (auto disable cache in dev env, auto enable in production env)
Domain
Debug: Also need to add lombok extension in IDE.
Lombok: Auto generate getter & setter methods and constructors, based on all final
properties
1 |
|
Related dependency:
1 | <dependency> |
Controller
Handle HTTP requests from client
Handling GET requests
1 | // Logger |
@Slf4j
: Simple Logging Facade for Java.
Lombok-provided annotation, auto generate logger at runtime
@GetMapping
& class-level @RequestMapping
:
When
/design
receives a HTTP GET request,showDesignForm()
will be called to handle the request@GetMapping
: New in Spring 4.3. Old method:1
2// lazy way, leave off the method attribute
All request-mapping annotations:
@RequestMapping
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
Model
: an object that transfers data between controller & view. ??
Data placed in Model
attributes is copied into the servlet response attributes, where the view can find them
Handling POST request
Fields in the form are bound to properties of a
Taco
object
1 |
|
Validate Form Input
The clumsy way: litter the controller with a bunch of
if / then
Recommended: Java Bean Validation API (JSR-303)
Validation API & its Hibernate implementation are auto added to the project as transient dependencies in the web starter.
Steps to apply validation:
- Declare validation rules in domain classes
- Specify validation should be performed in controller methods with
@PostMapping
- Modify views to display validation errors
Example 1
Taco domain:
1 |
|
Taco controller (添加 validation):
1 |
|
Example 2
Order excerpt:
1 | // Only make sure this isn't blank |
Order controller:
1 |
|
View Controllers
The controllers written so far:
- All annotated with
@Controller
: auto discovered by Spring component scanning, and instantiated as beans in the context - All annotated with
@GetMapping
,@PostMapping
: specify which method should handle what requests
A view controller: does not process data / input, only forward the GET
request to a view
Create a new config class for each kind of configuration (e.g. web, data, security)
1 |
|
- Registry: register one or more view controllers