'RestController Response with JSON vs. Controller Response with Model
I am studying sprint boot these days.And i'm trying develop a e-bank project with Spring boot. I can't understand why to could get direct response with JSON of restcontroller. I could use Model object with end-point that return of controller method. And i could process that model object to purpose on front-end side. But i don't know how to procces if i get response as JSON directly. If i could not, why could we return JSON directly? Can you explain these for me ?
You can take a look my restController and controller classes at my practice project
RestController response with JSON
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/rest/customer")
public class CustomerRestController {
private final CustomerService customerService;
@GetMapping("/{id}")
public Customer getCustomer(@PathVariable Long id) {
Optional<Customer> customer = customerService.getCustomer(id);
if(customer.isEmpty()) {
return null;
}
return customerService.getCustomer(id).get();
}
}
Controller Response with Model object
@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
@GetMapping("/{id}")
public String getCustomer(Model model, @PathVariable("id") Long id) {
Optional<Customer> customer = customerService.getCustomer(id);
if(customer.isEmpty())
log.error("Customer with id {} not found", id);
model.addAttribute("customer", customer.get());
return "customers/customer-profile";
}
}
I hope to explain myself and my question. Sorry about my english. Thank you :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
