Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chengyu Sun California State University, Los Angeles

Similar presentations


Presentation on theme: "Chengyu Sun California State University, Los Angeles"— Presentation transcript:

1 Chengyu Sun California State University, Los Angeles
CS5220 Advanced Topics in Web Programming Spring – RESTful Web Service Implementation Chengyu Sun California State University, Los Angeles

2 The SpringREST Example
REST API Using Spring and Hibernate

3 Comparison with Spring MVC
No more views @RestControler Message Converter using Jackson Many many other things stay the same Beans, …

4 Serialization/Marshalling and Deserialization/Unmarshalling
Java Object XML/JSON De-serialization/ Un-marshalling

5 Serialization/Deserialization in Spring
@RequestBody @ResponseBody void: empty response body + Status 200 Message converters Java object  request/response body When multiple converters are configured, Spring automatically choose which one to use based on Accept and/or Content-Type headers

6 HTTP Request Example POST /users HTTP/1.1 Host: localhost:8080
User-Agent: Mozilla/ Accept: application/xml Accept-Encoding: gzip,deflate Accept-Charset: utf-8 Content-Type: application/json Content-Length: … {“firstName”: “John”, “lastName”: “Doe”, “ ”: Request Line Headers Body (Optional)

7 HTTP Response Example HTTP/1.1 200 OK Status Line
Content-Type: application/json Content-Length: … Date: Sun, 03 Oct :26:57 GMT Server: Apache-Coyote/1.1 { “id”: 100, “firstName”: “John”, “lastName”: “Doe”, “ ”: “enabled”: true} Status Line Headers Body (Optional)

8 More About @RequestMapping
Be careful with the URL pattern Additional attributes method headers consumes produces

9 @RequestMapping Examples
@RequestMapping(value=“/users” consumes=“application/json”) Map the request to the method if the request’s Content-Type header is “application/json” @RequestMapping(value=“/users” produces=“application/json”) Map the request to the method if the request’s Accept header is “application/json”. Set the Content-Type header of the response to “application/json”.

10 More About REST API Implementation
Customize serialization/deserialization using Jackson annotations Handling errors and exceptions Testing

11 Serialization/Deserialization: Excluding Fields
Example: excluding password field from JSON response

12 Jackson Annotations (I)
@JsonIgnore @JsonIgnoreProperties value, e.g. {“password”, “enabled”} allowGetters allowSetters ignoreUnknown @JsonProperty value access, e.g. Access.WRITE_ONLY

13 Serialization/Deserialization: Handling Object Reference
Example: bi-directional association between User and Role

14 Adapt Model Design to Application Needs
Is bi-directional mapping necessary? Determine the right amount of data included in a response Example: User, Role, Ticket, Update

15 Jackson Annotations (II)
@JsonManagedReference for bidirectional association @JsonIdentityInfo handles multiple references to the same object generator = ObjectIdGenerators.PropertyGenerator.class property, e.g. id

16 Serialization/Deserialization: Value  Object
Example: add a User with the ADMIN role

17 Jackson Annotations (III)
@JsonValue indicates the property that will be used as the “value” of the object during serialization. @JsonCreator creates an object from a value during deserialization.

18 Errors and Exceptions Expected errors, e.g. login failure, missing required fields, …  need to inform client to correct the error Unexpected errors, i.e. exceptions  need to log problems for analysis and fix Error pages and redirects are not suitable for RESTful web services

19 Error Information for the Client
Status code, e.g. 401 Error message (Optional) application-specific error code

20 How to Send Back Error Information?
@RequestMapping(value = "/users", method = RequestMethod.POST) public User User user ) { if( user.username == null || user.password == null ) { ?? } return userDao.saveUser( user ); // database exception??

21 Problem with Java Exceptions
Too many checked exceptions Checked vs. Runtime exceptions Require lots of boilerplate exception handling code

22 Spring’s Solution to the Exception Problem
Use primarily runtime exceptions Separate exception handling code into exception handlers using AOP

23 Per-Controller Exception Handler Methods
public class SomeController { … … @ExceptionHandler(RestException.class) public ResponseEntity<Object> handleRestExceptions( RestException ex ) { … } @ExceptionHandler(Exception.class) handleOtherExceptions( Exception ex ) { … } }

24 Global Exception Handling Using @ControllerAdvice
public class SomeControllerAdvice { @ExceptionHandler(RestException.class) public ResponseEntity<Object> handleRestExceptions( RestException ex ) { … } @ExceptionHandler(Exception.class) handleOtherExceptions( Exception ex ) { … } }

25 Putting It Together Error Exception Response Exception Handler
An Error class that contains the information to be sent back to client. Additional exception classes can be created for different types of errors. Response Exception Handler A response to client is created using ResponseEntity Different exceptions can be mapped to different exception handlers

26 Logging Record events happened during software execution
During development During production

27 Requirements of Good Logging Tools
Support different message levels Fatal, error, warn, info, debug, trace Minimize performance penalty Support different log output Console, file, database, … Easy configuration

28 Java Logging Libraries
Logging implementations Log4j - java.util.logging in JDK Logging API Apache Commons Logging (JCL) - Simple Logging Façade for Java (SLF4J) -

29 Log4j Examples Log4j 1 with SLF4J – Logging Examples
Log4j 2 – Spring REST

30 Appender and Logger Apender Logger
Output type, e.g. console, file, database … Ouput format, i.e. layout Logger Package and/or class selection Message level

31 Testing REST API Manual testing with Postman
Automated testing with an application server and an HTTP client (e.g. HttpClient) Automated testing without an application server

32 Dependencies for MockMvc
org.springframework:spring-test A unit testing framework like JUnit or TestNG Additional JSON response testing JsonPath for traversing a JSON object Hamcrest for matchers

33 Example: UserControllerTest
Create a MockMvc Build requests using MockMvcRequestBuilders Use ResultMatchers to check the response Basic Spring ResultMatchers Additional JSON response testing using JsonPath and Hamcrest Matchers


Download ppt "Chengyu Sun California State University, Los Angeles"

Similar presentations


Ads by Google