0

I'm trying to forward a request from one controller to another controller and set a object in request so that the forwarded controller can use it in @RequestBody.

Following is the exact scenario:

Twilio calls a controller method with data sent by client as following:

@RequestMapping(value = "/sms", method = RequestMethod.POST)
public String receiveSms(@RequestParam("Twiml") String twiml, 
    HttpServletRequest request, 
    HttpServletResponse response) {

    //TODO - Create new instance of Activity and populate it with data sent from client
return "forward:/activity/new";
}

Now, I want to forward this request to ActivityController which already handles the request from web/rest clients. ActivityController.java has a method with following signature:

@RequestMapping(value = "/activity/new", method = RequestMethod.POST)
public ResponseEntity<Activity> updateLocation(
    @RequestBody Activity activity) {

}

Is it possible? If yes, how?

Thanks,

user1764832
  • 69
  • 3
  • 8

1 Answers1

1

Create the object and add it to the request as an attribute in the first controller,

request.setAttribute("object",new OwnObject()),
return "forward:/activity/new";

In the updateLocation Method retrieve that object from the request

@RequestMapping(value = "/activity/new", method = RequestMethod.POST)
public ResponseEntity<Activity> updateLocation(
    @RequestBody Activity activity, HttpServletRequest request) {
   OwnObject o = (OwnObject) request.getAttribute("object");
}
Eduardo Quintana
  • 2,368
  • 1
  • 15
  • 20
  • Twilio sends an XML request which contains the user sent data. I want to create an object of Activity object using those parameters and then forward it so that it gets available to method in ActivityController.java – user1764832 Feb 27 '14 at 16:57
  • You can add the Activity Object as a @RequestBody Object and it will map the xml to the object then add it to the request and forward it to updateLocation. – Eduardo Quintana Feb 27 '14 at 17:04
  • public String receiveSms(@RequestBody Activity activity, HttpServletRequest request, HttpServletResponse response){} – Eduardo Quintana Feb 27 '14 at 17:04
  • Since forward sends exactly the same call to all the handlers I think that creating the Activity Object and adding it as an attribute to the request will be reflected on the request received in updateLocation. – Eduardo Quintana Feb 27 '14 at 17:11
  • That worked, just need to mark Activity in ActivityController to required = false [@RequestBody(required = false)] – user1764832 Feb 27 '14 at 17:33