Skip to content

True Content-Negotiation [SPR-13679] #18254

Closed
@spring-projects-issues

Description

@spring-projects-issues

Enrique Ruiz (DiSiD) opened SPR-13679 and commented

Spring MVC provides three ways to support Content-Negotiation but IMHO it isn't a true CN because really only one method in the Controller cannot handle several formats requested by the user.

Due to the current CN depends on annotations in the handler methods a developer has to create 4 methods to support all the possible combinations:

  • @RequestParam + @ResponseBody: received data as parameters and returned data as a JSON message
  • @RequestParam + View: received data as parameters and returned data as HTML
  • @RequestBody + @ResponseBody: received data as JSON message and return message as a JSON message
  • @RequestBody + View: received data as JSON message and return message as HTML

Although you can delegate between these methods you have to maintain 4 methods that potentially will change along the time and could evolve to different implementations, so really you are duplicating control logic.

What is true CN? For me true CN is to choose the conversion and binding of the incoming parameters or the conversion and binding of the request body depending on the HTTP "Content-Type" header property of the request.

In the same way, the conversion and formatting of the model objects included in the response could be by using a View or a MessageConverter depending on the HTTP "Accept" header property of the request.

Of course, the logical view-name should be infered from the URL automatically if needed, for example by using a DefaultRequestToViewNameTranslator.

By doing that only one handler method is needed and we won't duplicate control logic. For example:

@Controller
class AccountController {

  @RequestMapping("/accounts")
  @ResponseStatus(HttpStatus.OK)
  public List<Account> list(Principal principal) {
    return accountManager.getAccounts(principal);
  }

}

Affects: 4.2.2

Issue Links:

5 votes, 5 watchers

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions