When my commandButton
s for signup
and login
call their methods in their backing beans I would like to redirect to index
when succeeded, and stay on same view when fails. That all works fine, I return "index?faces-redirect=true"
on success. I case of a fail I realized now, that I have different possibilities: I could return "signup"
(or "login"
), also ""
works, and even when I return null
I get the same result. At least I can not detect any differences.
Is there a common style what to return, when the result should be the same view?
I could return "signup"
(or "login"
), also ""
works, and even when I return null
I get the same result. At least I can not detect any differences.
There is actually a technical difference with regard to null
and non-null
outcomes. The null
(or void
) outcome will reuse the same view. A non-null
outcome will trash the current view and create a brand new view, even if it returns the same view identifier. The "view" is here the UIViewRoot
instance including all of its state. The empty string represents "current view ID".
Notably @ViewScoped
beans are affected by this. They will be trashed and recreated along with the view. If you're however using a @RequestScoped
bean, then you indeed won't notice any technical difference as to bean behavior. It won't be trashed when the view gets trashed, but only when the request ends. In other words, even when the same view is recreated within the same request, the same @RequestScoped
bean will be used on it.
The right approach depends on the concrete functional requirements. If you want to return to the same view, just return null
or void
(not empty string). It's generally unnecessary to create a new view in such case. Only if you're having view build time tags (JSTL and friends) in current view whose model values have been changed in bean action method, then you'd need to force a rebuild of the view by returning an empty string. If you want to navigate to a different view, return the desired view identifier, preferably along with faces-redirect=true
, for sure if it's idempotent (bookmarkable).
See also:
- How to navigate in JSF? How to make URL reflect current page (and not previous one)
- Difference between View and Request scope in managed beans
- What's the view build time?