Spring REST

Last Updated on: February 17, 2021 am

Java JSON Data Binding

Data binding is the process of converting the JSON data to a Java POJO.

Also known as: Mapping, Serialization/Deserialization

Jackson Data Binding

Spring uses the Jackson Project behind the scenes.

Jacksong supports XML and JSON.

By Default, Jackson will call appropriate getter/setter methods.

JSON to Java POJO

Jackson will call setXXX() methods

Java POJO to JSON

Jackson will call getXXX() methods

Spring and Jackson Support

Spring will automatically handle Jackson Integration.

JSON data being passed to REST Controller is converted to POJO.

Java Object being returned from REST controller is converted to JSON.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Driver {
public static void main(String[] args) {
try {
// create the object mapper
ObjectMapper mapper = new ObjectMapper();
// read JSON file and map/convert to Java POJO
// data/sample-lite.json
Student theStudent = mapper.readValue(
new File("data/sample-full.json"), Student.class);
//print the first name and last name
System.out.println("First Name:"+theStudent.getFirstName());
Address address = theStudent.getAddress();
System.out.println("Street: "+address.getStreet());
for(String lan: theStudent.getLanguages()){
System.out.println(lan);
}
} catch (Exception e){
e.printStackTrace();
}
}
}

Ignore Unknown Properties

Add a new annotation: @JsonIgnoreProperties

1
@JsonIgnoreProperties(ignoreUnknown = true)

REST HTTP

HTTP Request Message

  • Request Line: the HTTP command
  • Header Variables: Request Metadata
  • Message Body: contents of Message

HTTP Response Message

  • Request Line: server protocol and status code
  • Header Variables: Response Metadata
  • Message Body: contents of Message

Status Code

MINE Content Types

MINE - Multipurpose Internet Mail Extenstion

Basic Syntax: type/sub-type

Examples:

  • text/html, text/plain
  • application/json, application/xml

Client Tool

send HTTP requests - Postman

Spring REST Controller

@RestController

  • Extension of @Controller
  • Handles REST request and responses
1
2
3
4
5
6
7
8
@RestController
@RequestMapping("/test")
public class DemoRestController {
@GetMapping("/hello")
public String helloWorld(){
return "Hello World!";
}
}

Note: Config Spring MVC just like previous. Then change @Controller to @RestController

Retrieve JSON from POJO

1
2
3
4
5
6
7
8
9
10
11
@RestController
@RequestMapping("/api")
public class StudentRestController {
@GetMapping("/students")
public List<Student> getStudent(){
List<Student> students = new ArrayList<>();
students.add(new Student("Ashley", "Ma"));
students.add(new Student("Machine", "Ma"));
return students;
}
}

Note: Jackson will automatically handle all the low-level operations to convert the POJO to JSON format objects and display in the Response Body.

Use @PathVariable for REST Endpoints

1
2
3
4
@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId){
return students.get(studentId);
}

Exception Handling

1
2
3
4
5
6
7
8
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(Exception exc){
StudentErrorResponse err = new StudentErrorResponse();
err.setMessage(exc.getMessage());
err.setStatus(HttpStatus.BAD_REQUEST.value());
err.setTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>(err, HttpStatus.BAD_REQUEST); // err is the body and 404 is status code
}