Returning to same view in backing bean, should I r

2019-08-15 03:00发布

When my commandButtons 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?

1条回答
2楼-- · 2019-08-15 04:02

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:

查看更多
登录 后发表回答