Is there a way to forward a request to another Controller while adding some parameter data to it? I tried adding to the ModelMap, but it doesn’t seem to hang around. I am doing something like:
return "forward:/my-other-controller";
Only other way I can think of is to put the parameters on the session and then pop them off in the target controller.
The simplest way is to add the data to the request. Since this is a forward, the same request is passed around to different handlers within the server.
As example, let’s start with a simple setup of two controllers, one forwarding to the other:
First way to add the data is to set it as attributes on the request. The new controllers will look like this (A):
Since the view name in the forward prefix is basically an URL, you can also have the following versions (attribute changed to parameter) (B):
You can also further simplify the second controller by using annotations instead:
And just for the fun of it, and to show Spring’s binding behavior in action, you could do it even like this (C):
I would personally go with solution A for many parameters, and solution B for a few. Solution C has a sort of “huh…?!” effect so I would avoid it (also it works with parameters added to the URL so a few of those or you get a messy URL).
Adding the data in the session would also work off course, but would extend the data’s life time unnecessarily, so the best place is to add it on the request during the transition to the second controller.