김태오

Parameter handling in Controllers 본문

Spring Boot

Parameter handling in Controllers

ystc1247 2023. 7. 15. 16:10

When handling requests from the client in the controller, there are various choices of lombok annotations to select from. The frequently used ones are @RequestBody, @ModelAttribute, @RequestParam, @PathVariable.

In this post, I will discuss the pros and cons of each and the suitable situations to use them.

 

@RequestBody vs @RequestParam

 

@RequestParam often handles GET requests, where the data that is sent is a simple datatype like Long, String, Boolean etc. It maps single parameters in the request, so when trying to map multiple parameters, multiple @RequestParam annotations are needed for each request.

@GetMapping("/user")
    public String getUser(@RequestParam String name) {
        return "Requested user: " + name;
    }

If I made a /user?name=theo in this request, it will return "Requested user: theo".

 

@RequestParam is used in handling PUT and POST requests, where the data sent is more complex than the GET request. It is often a entity or a data transfer object itself.

@RestController
public class UserController {

    @PostMapping("/user")
    public String createUser(@RequestBody User user) {
        return "Created user: " + user.getName();
    }
}

class User {
    private String name;
    private int age;

    // getters and setters
}

The HTTP POST request in the /user controller here will be a JSON format, for example { "name" : "theo", "age" : 22 }. It will create a User object with the name attribute of "theo" and the age attribute of 22. The controller will return "Created user: theo".

 

@ModelAttribute vs @RequestBody

The @ModelAttribute annotation is the one that I had used mostly in passing parameters.

The main difference between the two is that @ModelAttribute is used when your data is coming as form parameters, while @RequestBody is used when your data is in the request body, often as JSON or XML.

 

@PathVariable

This is used when extracting variables from the URL itself. 

@GetMapping("/user/{userId")
    public String searchUser(@PathVariable Long userId) {
        // logic to search user
        return "User searched with name " + user.getName();
    }

Summary : 

  1. @RequestParam: This is commonly used in GET requests to specify URL parameters, or sometimes in POST requests for form data. This is often used for simple data types and when data is optional.
  2. @PathVariable: This annotation is used to extract variables from the URL itself. It's frequently used in RESTful web services where URLs often contain a resource identifier.
  3. @RequestBody: This is typically used with POST, PUT, and PATCH requests where significant data is being sent in the body of the request, often in JSON or XML format. It is necessary when you want to send a full object or a complex nested object to the backend.
  4. @ModelAttribute: This is used to bind request parameters to a JavaBean object. This is often used when you are handling form submission and you have an object with fields that match the form fields.

'Spring Boot' 카테고리의 다른 글

FeignClient 사용시 PATCH method 가 안되는 오류  (0) 2024.03.11
async 작업 시 thread 의 traceId 전파  (0) 2024.03.09
동일성과 동등성  (0) 2023.11.29
@Getter 와 @Setter 남용  (0) 2023.11.02
JpaAuditing  (0) 2023.04.10