3

I have spring boot application which used spring rest controller . This is the controller , below is the response an getting. Am using postman tool for sending request to this controller. And am sending content type as application/json

    @RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody WebApp webapp, @RequestBody String propertyFiles, @RequestBody String) {
    System.out.println("webapp :"+webapp);
    System.out.println("propertyFiles :"+propertyFiles);
    System.out.println("propertyText :"+propertyText);

    return "ok good";
}

2018-03-21 12:18:47.732  WARN 8520 --- [nio-8099-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed

This is my postman request

{
"webapp":{"webappName":"cavion17","path":"ud1","isQA":true},
"propertyFiles":"vchannel",
"propertytText":"demo property"}

I tried by removing the RequestBody annotation, then able to hit the service , but param objects are received as null.

So please suggest how to retrieve objects in the restcontroller?

Ansar Samad
  • 509
  • 2
  • 6
  • 12

2 Answers2

8

You cannot use multiple @RequestBody annotations in Spring. You need to wrap all these in an object.

Some like this

// some imports here
public class IncomingRequestBody {
    private Webapp webapp;
    private String propertryFiles;
    private String propertyText;

    // add getters and setters here
}

And in your controller

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody IncomingRequestBody requestBody) {
    System.out.println(requestBody.getPropertyFiles());
    // other statement
    return "ok good";
}

Read more here Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Yuvraj Jaiswal
  • 1,317
  • 9
  • 16
1

Based on the sample postman payload you gave, you will need:

public class MyObject {

    private MyWebapp  webapp;
    private String propertyFiles;
    private String propertytText;

    // your getters /setters here as needed
}

and

public class MyWebapp {
    private String webappName;
    private String path;
    private boolean isQA;

    // getters setters here
}

Then on your controller change it to:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody MyObject payload) {
    // then access the fields from the payload like
    payload.getPropertyFiles();

    return "ok good";
}
geneqew
  • 1,877
  • 3
  • 25
  • 42