Junior — Middle
What actions should a controller perform in MVC when processing a request to create a new object?
sobes.tech AI
Answer from AI
In an MVC controller, when processing a request to create a new object, the following actions are usually performed:
- Receive data from the request (for example, from the body of a POST request).
- Validate the input data, checking its correctness.
- Call the service layer or interact directly with the model to create a new object.
- Handle possible errors (such as constraint violations or validation errors).
- Formulate a response to the client, for example, confirming successful creation or with an error message.
Example in Java using Spring MVC:
@PostMapping("/items")
public ResponseEntity<Item> createItem(@RequestBody @Valid ItemDto itemDto) {
Item newItem = itemService.create(itemDto);
return new ResponseEntity<>(newItem, HttpStatus.CREATED);
}
Here, the controller accepts a DTO, validates it, calls the service to create, and returns the created object with a 201 status code.