Spring MVC Flashcards
Explain the MVC architecture and how HTTP requests are processed in the architecture
The Model-View-Controller (MVC) framework is an architectural pattern that separates an application into three main logical components Model, View, and Controller
A Controller handles all the HTTP requests and responses
What is the role of the DispatcherServlet? What about the ViewResolver?
The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that’s supposed to be found at that location.
The ViewResolver provides a mapping between view names and actual views
List some stereotype annotations. What are the differences between these?
@Component: Indicates class is a parent
@Service: handle business logic in conjunction with a persistance layer
@Repository: handle CRUD operations against a DB
@Controller: handles web requests
@Configuration
How would you declare which HTTP requests you’d like a controller to process?
By adding a certain path to the @RequestMapping in a controller method
What is the difference between @RequestMapping and @GetMapping?
@GetMapping is just a more specific @RequestMapping. Meaning you could also use @RequestMapping(method = RequestMethod.Get)
How to declare the data format your controller expects from requests or will create in responses?
HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add(“Content-Type”, “text/html; charset=utf-8”);
What annotation would you use to bypass the ViewResolver?
@ResponseBody
How would you extract query and path parameters from a request URL in your controller?
You would use @QueryParam in the method
What concerns is the controller layer supposed to handle vs the service layer?
A controller handles requests and then tells the service what it needs. A controller is like a manager and the service is like an employee.
How would you specify HTTP status codes to return from your controller?
@ResponseStatus above a method and it will only work when the method completes successfully otherwise it will send and html error page to the client
How do you handle exceptions thrown in your code from your controller? What happens if you don’t set up any exception handling?
Use @ExceptionHandler or @ControllerAdvice in conjunction with @ResponseStatus
How would you consume an external web service using Spring?
Create a REST Template Bean
Use @GetMapping
Use getForObject
What are the advantages of using RestTemplate?
It simplifies the interaction with HTTP servers and enforces RESTful systems.