For simplicity's sake, these code snippets will be shortened. The purpose of this is to take a GET parameter, set it on the session, and redirect back to the GET with the url parameter removed. Basically, URI cleanup. If there's a better/simpler way to do this, I would be glad to hear it.
I have a controller defined as such:
@Controller
@RequestMapping("/path/page.xhtml")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@SessionAttributes({ "myParam1", "myParam2" })
public class MyController {
@RequestMapping(method = RequestMethod.GET, params = { "urlParam2" })
public String handleUriParam(@RequestParam(value = "urlParam2", required = false)
final Long urlParam2,
final RedirectAttributes redirs) {
// at this point, myParam1 is set on the session.
// now set the param as a flash attrib with the name of the session variable
redirs.addFlashAttribute("myParam2", urlParam2);
return "redirect:/path/page.xhtml";
}
@RequestMapping(method = RequestMethod.GET, params = {})
public String doGetStuff(ModelMap model) {
// do stuff using myParam1 and myParam2.
// problem is, myParam2 is on the session, but myParam1 is not!
}
}
Like the code says, somehow myParam1
is being un-set when the redirect happens. I can fix this by passing a ModelMap
to the handleUrlParam
method and manually adding myParam1
to the flash attributes, but that seems to defeat the purpose in my mind.
Why is the SessionAttribute
myParam1
being removed after the redirect?
Is there a better way to pull parameters off the URI and put them on the session?
UPDATE
So it seems that whenever you use RedirectAttributes
at all, you must make sure you put any SessionAttribute
s you want to carry into the redirect on the FlashAttributes or else they will be lost. I imagine this happens because SessionAttribute
s are pulled off the ModelMap
(which is replaced by FlashAttributes when used). Is this a bug in Spring or intentional behavior? If it's intentional, can someone explain why? I thought SessionAttribute
s were meant to stay on until removed by completion of the conversational session.
Similar StackOverflow post here.
Addendum
In light of the accepted answer provided, I am still stumped as to how I can clear the URI parameters while putting them on the user's session. One option I have considered is to create a wrapper for the semi-primitive objects (java.lang.Integer, java.lang.String) I am trying to store because they will not be placed on the URI string, but this seems hacky to me. If anyone has a better way to accept GET parameters, store them on the user's session, and clear those from the user's address bar (which will require a redirect), I will gladly use it.
See Question&Answers more detail:
os