liveBook · Manning

Web API action method

As explained in Spring Start Here, Second Edition

A controller action is a controller method associated with an HTTP request and responsible for producing the request's response.

A controller action is a method associated with an HTTP request. When a matching request arrives, Spring executes the action and uses its result to produce a response. Actions can serve web pages or expose REST endpoints for communication between applications. section 7.3 section 10.1

A page action

Put home.html in resources/static, then define a controller action mapped to /home. The action returns "home.html", a reference to the page to serve. A browser can request the mapped path and display the returned HTML. section 7.3

Listing 7.5 The definition of the controller class
@Controller    #A
public class MainController {
 
  @RequestMapping("/home")  #B
  public String home() {
    return "home.html";    #C
  }
}

The controller uses @Controller to identify the class and @RequestMapping to associate the home() action with /home. section 7.3

For a REST endpoint, an action is mapped to an HTTP method and path, but its result is sent to the client rather than used to find a view. Use @ResponseBody on a method or @RestController on the class to return the response body directly. Without either, the dispatcher servlet assumes the result is a view name. section 10.1 section 10.6

A REST action can also:

  • Receive client data through request parameters, path variables, or the HTTP request body. section 10.6
  • Return a ResponseEntity to control the HTTP status and headers, or return a body and rely on Spring’s default status behavior. section 10.6
  • Handle an exception itself or leave exception handling to a REST controller advice class. Handling it in the action couples the handling logic to that action and can lead to duplication. section 10.6

An action that takes too long can cause the HTTP call to time out. Large requests and too many concurrent calls can also cause communication or application problems. section 10.1

How Spring Start Here, Second Edition covers it

How deep it goes
Explains request mapping and response flow, then outlines response control, request inputs, and exception handling.
Examples
Shows a home() action mapped to /home that returns a reference to home.html.
What you can do after
Apply it via Spring MVC to map requests to actions and configure REST response bodies, statuses, and headers.
How it connects
Connects controller actions to Spring MVC, HTTP requests, REST endpoints, view resolution, and exception handling.

Also explained in

Compare how 4 books explain web API action method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.