springmvc & rest

17
Spring MVC & REST M1 PROJET - 2018-2019 (images: pixabay) Philippe Collet 1

Upload: others

Post on 16-Jun-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SpringMVC & REST

Spring MVC & REST

M1 PROJET - 2018-2019 (images: pixabay) Philippe Collet 1

Page 2: SpringMVC & REST

Outline• General Principles

• Configuration

• Annotations and Process

• RESTful Webservices

• Consuming a Web Service

2

Page 3: SpringMVC & REST

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

Page 4: SpringMVC & REST

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.

Page 5: SpringMVC & REST

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

Page 6: SpringMVC & REST

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

Page 7: SpringMVC & REST

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

Page 8: SpringMVC & REST

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.

Page 9: SpringMVC & REST

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.

Page 10: SpringMVC & REST

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

Page 11: SpringMVC & REST

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

Page 12: SpringMVC & REST

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

Page 13: SpringMVC & REST

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

Page 14: SpringMVC & REST

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

Page 15: SpringMVC & REST

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

Page 16: SpringMVC & REST

• 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

Page 17: SpringMVC & REST

• 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