Home > Blockchain >  Spring - Post Mapping
Spring - Post Mapping

Time:11-21

Is there a way that when you have a code:

@PostMapping("/test")
public boolean test(@RequestBody String data) {
    //code and stuff
}

You could send information in the post request url? for example

localhost:8080/test?username=username

CodePudding user response:

You can use the @RequestParam annotation.

@PostMapping("/test")
    public boolean test(@RequestBody String data, @RequestParam String username) {
    //code and stuff
}

If you need to call it something else you can also specify that

@RequestParam("username") String whatever

CodePudding user response:

You can mix request body and request params.

In your example, you can read the username request param this way:

@PostMapping("/test")
public boolean test(@RequestBody String data, @RequestParam String username) {
    //code and stuff
}

CodePudding user response:

Yes, just use @RequestParam:

@PostMapping("/test")
public boolean test(@RequestParam String username, @RequestBody String data) {
    //code and stuff
}

In the reference documentation we can read the following:

Supported for annotated handler methods in Spring MVC and Spring WebFlux as follows:

  • In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests. This is because the Servlet API combines query parameters and form data into a single map called "parameters", and that includes automatic parsing of the request body.
  • In Spring WebFlux, "request parameters" map to query parameters only. To work with all 3, query, form data, and multipart data, you can use data binding to a command object annotated with ModelAttribute.
  • Related