Spring MVC & REST M1 PROJET - 2018-2019 (images: pixabay) Philippe Collet 1
Spring MVC & REST
M1 PROJET - 2018-2019 (images: pixabay) Philippe Collet 1
Outline• General Principles
• Configuration
• Annotations and Process
• RESTful Webservices
• Consuming a Web Service
2
Introduction
• Spring MVC helps in building flexible and loosely coupled web applications.
• The Model-view-controller design pattern helps in separating– the business logic, – presentation logic,– navigation logic.
• Models are responsible for encapsulating the application data– In general, they are POJOs
• The Views render response to the user with the help of the model object– For example, HTML output
• Controllers are responsible for receiving the request from the user, calling the back-end services, and passing the resulting model to the right view
3
Spring MVC architecture and behavior
4
1. The DispatcherServlet first receives the request and consults the HandlerMapping
2. The DispatcherServlet invokes the Controller associated with the request. The Controller process the request by calling the appropriate service methods and returns the view name to the DispatcherServlet. │ It can also be an ModelAndView object containing the model data and the view name.
3. The DispatcherServlet sends the view name to a viewResolver to find the actual View to invoke.
4. Now the DispatcherServletwill pass the model object to the View to render the result. │ The View with the help of
the model data will render the result back to the user.
Configuration• We need to map requests that we want the DispatcherServlet to handle, by using a URL
mapping in the web.xml file (kept in the WebContent/WEB-INF directory)– Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application
context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory
5
If you do not want to go with default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listenerContextLoaderListener in your web.xml
Configuration
• In the MVC configuration file (HelloWeb-servlet.xml in our example) :
6
Beans definition override the definitions of any beans defined with the same name in the global scope
<context:component-scan...> and <mvc:annotation…> activates Spring MVC annotation scanningcapability which allows to make use of annotations like @Controller and @RequestMapping
InternalResourceViewResolver has rules to resolve the view names. As per the above defined rule, alogical view named hello is delegated to a view implementation located at /WEB-INF/view/hello.jsp
Annotations• The DispatcherServlet delegates the request to the controllers to execute the
functionality specific to it. – The @Controller annotation indicates that a particular class is a controller. – The @RequestMapping annotation is used to map a URL to either an entire class or a particular
handler method.
• Simply @Autowire to access to other Spring components in the Controller
7
indicates that all handling methods on thiscontroller are relative to the /hello path
used to declare theprintHello() method as the controller'sdefault service method to handle HTTP GET request
Annotations
8
The value attribute indicates the URL to which the handler method is
mapped and the method attribute defines the service method to
handle HTTP GET request.
A ModelMap is passed as parameter.
You can use it to set different model attributes and
these attributes will be accessed by the view to
present the final result.
This example modifies the model with its attribute
"message".
�Other option: enables a multi-actions controller class that is able to serve multiple different requests
return a String, which contains the
name of the view to be used to
render the model. This example
returns "hello" as logical view name.
View: example with a simple JSP
9
${message} is the attribute which wehave set up inside the Controller.
You can have multiple attributes to bedisplayed inside your view.
�/WEB-INF/view/hello.jsp
�Spring MVC also supports many types of views for different presentation technologies: │ JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, etc.
Parameters and path variables
10
• URL: http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013• Gets the invoices of the user with id 1234 for the date of December 5th, 2013
PathVariable: to obtain some placeholderin an URI Template
Here the variable is named as it isdifferent from the method parameter
Can be used in any RequestMethod
RequestParam: to obtain a parameterfrom the URL
Can be optional
A basis for web services implementation• Spring MVC is already seving Web Content with @Controller and @Mapping
• A RESTful Web Service in Spring?• - Think REST (Representational State Transfer)• - Use new @RestController
• REST-compliant Web services allow the requesting systems to access and manipulatetextual representations of web resources by using a uniform and predefined set of stateless operations- a base URL- media type (JSON is default in Spring 4)- standard HTTP methods for interaction (e.g., OPTIONS, GET, PUT, POST, and DELETE)
GET /tickets - Retrieves a list of ticketsGET /tickets/12 - Retrieves a specific ticketPOST /tickets - Creates a new ticketPUT /tickets/12 - Updates ticket #12PATCH /tickets/12 - Partially updates ticket #12DELETE /tickets/12 - Deletes ticket #1
11
RESTful Web services in Spring
• Example:• http://localhost:8080/greeting• that should answer in JSON format:• {"id":1,"content":"Hello, World!"}
• http://localhost:8080/greeting?name=User
• Which is a customized version returning:• {"id":1,"content":"Hello, User!"}
12
RESTful Web services in Spring• A Resource representation
class:– the id field is a unique
identifier for the greeting– content is the textual
representation of the greeting
• The service should:– handle GET requests
for /greeting, optionallywith a name parameter in the query string
– The GET request shouldreturn a 200 OK responsewith JSON in the body thatrepresents a greeting
13
14
• @RestController class : the GreetingController handles GET requestsfor /greeting by returning a new instance of the Greeting class.– The @RequestMapping annotation ensures that HTTP requests to /greeting are
mapped to the greeting() method– does not specify GET vs. PUT, POST, and so forth, because @RequestMapping maps
all HTTP operations by default. Use @RequestMapping(method=GET)– @RequestMapping does not specify GET vs. PUT, POST, because it maps all HTTP
operations by default. Use @RequestMapping(method=GET) or @GetMapping("/greeting") to narrow it
Consuming a RESTful Web service• Let us consider the RESTful service that randomly fetches quotes
about Spring Boot and returns them as a JSON document:• http://gturnquist-quoters.cfapps.io/api/random
• Spring provides a convenient template class called RestTemplate– RestTemplate makes interacting with most RESTful services a one-line
invokation– It can bind that data to custom domain types.
15
• A domain class with the data we need– @JsonIgnoreProperties fro
m the Jackson JSON processing library to indicate that any propertiesnot bound in this type should be ignored
– Specify the variable nameexact same as the key in the JSON Document returnedfrom the API.
– In case your variable nameand key in JSON doc are not matching, use @JsonPropertyannotationto specify the exact key of JSON document
16
• An additional class is needed to embedthe inner quotation itself
• Then, the RestTemplate can be used:RestTemplate restTemplate = new RestTemplate(); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
• RestTemplate will use the Jackson JSON processing library (via a message converter) to convert the incomingJSON data into a Quote object
17