You are on page 1of 17

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
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 DispatcherServlet
will 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.

4
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

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 listener
ContextLoaderListener in your web.xml

5
Configuration
• In the MVC configuration file (HelloWeb-
servlet.xml in our example) :

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 scanning


capability 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, a
logical view named hello is delegated to a view implementation located at /WEB-INF/view/hello.jsp

6
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

indicates that all handling methods on this


controller are relative to the /hello path

used to declare theprintHello() method as the controller's


default service method to handle HTTP GET request
7
Annotations
Other option: enables a multi-actions controller class that is able to serve multiple
ž

different requests
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.

return a String, which contains the A ModelMap is passed as parameter.


name of the view to be used to You can use it to set different model attributes and
render the model. This example these attributes will be accessed by the view to
returns "hello" as logical view name. present the final result.
This example modifies the model with its attribute
"message".

8
View: example with a simple JSP
/WEB-INF/view/hello.jsp
ž

${message} is the attribute which we


have set up inside the Controller.

You can have multiple attributes to be


displayed inside your view.

Spring MVC also supports many types of views for different presentation technologies:
ž

│ JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, etc.

9
Parameters and path variables
• 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 placeholder RequestParam: to obtain a parameter


in an URI Template from the URL

Here the variable is named as it is Can be optional


different from the method parameter

Can be used in any RequestMethod


10
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 manipulate
textual 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 tickets


GET /tickets/12 - Retrieves a specific ticket
POST /tickets - Creates a new ticket
PUT /tickets/12 - Updates ticket #12
PATCH /tickets/12 - Partially updates ticket #12
DELETE /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?na
me=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, optionally
with a name parameter in
the query string
– The GET request should
return a 200 OK response
with JSON in the body that
represents a greeting
13
• @RestController class : the GreetingController handles GET requests
for /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

14
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 properties
not bound in this type
should be ignored
– Specify the variable name
exact same as the key in the
JSON Document returned
from the API.
– In case your variable name
and key in JSON doc are not
matching, use
@JsonPropertyannotation
to specify the exact key of
JSON document

16
• An additional class is needed to embed
the 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 incoming
JSON data into a Quote object

17

You might also like