@ModelAttribute vs @RequestBody in Validation
1. What is @ModelAttribute?
What does it do?
@ModelAttribute is primarily used to bind request data like HTML form data or query parameters (e.g., ?name=abc&price=100) to objects. In other words, it converts data entered by users in forms into objects that can be easily handled by controllers.
How does it work?
It maps HTTP request parameters (e.g., name, price) individually to object properties on a field-by-field basis. For example, if an ItemSaveForm object has name and price fields, request parameters name="book" and price=1000 would be set as itemSaveForm.setName("book"), itemSaveForm.setPrice(1000).
Important characteristic: Even if there's a problem with one field (e.g., price has an invalid value like "abc" that can't be converted to a number), the other fields (e.g., name) are still bound normally. It has a structure that can partially succeed.
Advantages:
- Flexibility: Since it processes on a field-by-field basis, even if certain fields have errors, the rest can be processed normally.
- Validation: You can validate objects using @Valid or @Validated. For example, you can apply rules like name must not be empty or price must be greater than 0.
- Easy error handling: If a binding error occurs in a specific field, Spring puts the error in a BindingResult and passes it to the controller, making it easy for developers to handle errors.
- Form data: name=book&price=1000 → Normal binding.
- Form data: name=book&price=abc → price binding fails, but name is bound normally and error information is stored in BindingResult.
- When processing HTML form data (e.g., data submitted with a <form> tag).
- When receiving data through query parameters.
- When flexible binding and validation on a field-by-field basis are needed.
2. What is @RequestBody?
When does it do?
@RequestBody is mainly used to convert data sent in the HTTP request body in formats like JSON or XML into objects. For example, when a client sends JSON data via a REST API, it converts that data into a Java object.
How does it work?
It converts the request body data into an object all at once. Spring uses HttpMessageConverter (e.g., MappingJackson2HttpMessageConverter for JSON) to convert JSON data into Java objects.
Important characteristic: The conversion process is all or nothing. If the JSON data cannot be properly converted to an object (e.g., wrong JSON format or mismatched field types), an exception (usually HttpMessageNotReadableException) occurs and the controller itself is not called.
Advantages:
- Clean mapping of structured data like JSON or XML to objects.
- Suitable for data exchange between clients and servers in REST APIs.
- Lack of flexibility: If JSON → object conversion fails, an exception is thrown immediately and doesn't reach the controller. In other words, partial binding is impossible.
- Validation constraints: When conversion fails, validation logic like @Valid or @Validated won't run. Validation is only possible after successful conversion.
- Complex error handling: Since JSON parsing errors occur outside the controller, separate exception handling logic (e.g., @ExceptionHandler) is needed.
- Request body: {"name": "book", "price": 1000} → Normal conversion, controller called.
- Request body: {"name": "book", "price": "abc"} → JSON parsing fails, exception occurs, controller not called.
When to use it?
- When receiving JSON or XML data through REST APIs.
- When structured data in the request body needs to be converted to an object all at once.
3. Understanding with Simple Analogies
@ModelAttribute
- Think of it like assembling Lego blocks one by one.
- Each parameter (Lego block) is attached to the object (finished product) one by one.
- Even if a certain block doesn't fit (e.g., wrong type), you can still attach other blocks.
- You can also validate the completed parts (e.g., check if the finished product is properly made).
@RequestBody
- This is like receiving a completed Lego set all at once and using it as is.
- It converts the JSON (completed set) sent by the client into an object all at once.
- If the set is wrong or even one part is incorrect (e.g., JSON format error), you can't even open it.
- Validation (e.g., checking if the set is the desired shape) can only begin if a proper set arrives.
Comments
Post a Comment