1 of 5

Spring Java framework

K. V. Raghavan

Indian Institute of Science, Bangalore

2 of 5

HTTP

  • Is a stateless, connectionless, synchronous (i.e., request-response) protocol
    • That is, the protocol itself does not maintain any state about the request-responses so far between the the same client-server pair
  • A request has a mandatory “start line” plus optional headers plus optional body
    • Start line contains request method, request-path, request parameters, etc.
      • e.g., GET /index.html HTTP/1.1
    • Note, URL and port are not in the request, the request is sent to the URL:port
    • PUT and POST have body/payload
    • Browser address bar shows only URL, port, request-path, request params
  • A response has a status code, optional headers, optional body

3 of 5

What is Spring?

  • A simplified way to construct web applications, web services, and much more
  • Sample Spring guides that we will go over

4 of 5

Selected Spring annotations

  • @SpringBootApplication: the "main" class should have it
  • @RestController:
    • used against a class that handles web requests if its methods return strings directly to the client (i.e., do not redirect to a view)
    • Each method can either return a String, or an arbitrary object, which Spring will automatically serialize into a JSON string
  • @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping:
    • used against a method to indicate which incoming requests to map to this method, based on URL - HTTP Method combination
  • @RequestParam:
    • a way to bind request parameters to method parameters. See https://spring.io/guides/gs/rest-service/

5 of 5

Selected Spring annotations - II

  • @PathVariable: The following code fragment explains this:

@GetMapping("/api/employees/{id}")

public String getEmployeesById(@PathVariable String id) {

return "ID: " + id;

}

  • @RequestBody: Consider the following example:

@PostMapping("/request")

public ResponseEntity postController(@RequestBody LoginForm loginForm) {

exampleService.fakeAuthenticate(loginForm);

return ResponseEntity.ok(HttpStatus.OK);

}

The payload of the POST request (which has to be JSON format) automatically gets deserialized into the parameter object loginForm

  • Java Persistence (JPA) and ORM: to be introduced later