2

可能重复:
如何选择正确的 bean 范围?

我是 JSF 编程的新手,我需要澄清一下 bean 范围。我已经阅读了有关此论点的所有问题,但不是很清楚。我不太了解请求范围。我明白:“这是默认范围,基本上 bean 在单个 HTTP 请求中都是活动的。”

例如,假设我们要求浏览器打开一个带有表单的网页。当我们发出请求时,会创建一个请求范围 bean,生命周期开始,在渲染响应阶段之后,Java bean 被销毁。然后我们填写表格并按下按钮。这将启动另一个 HTTP 请求,对吧?

在相同的上下文中,如果一个有视图范围 bean 而不是请求范围 bean,有什么区别?创建了多少个 bean 实例?为什么将它与数据表一起使用会更好?

4

1 回答 1

2

The request scope as all your sources including the post linked by BalusC say starts living a short while after your request hits the server, and is destroyed shortly after the last bit of the response has been send back.

Indeed, if you postback a form a new request starts and thus a new request scope. This means everything that is request scoped will be created again. So for a form that is first rendered, and then posted back once, 2 request scoped beans will be created.

The view scope lives as long as you do postbacks to the same view (page). This works by means of the hidden form parameter called javax.faces.ViewState. The value of this is an entry into some kind of logical Map if you use save state on server. How a JSF implementation actually resolves this is not that important here (but yes, it's mostly just a Map).

After the postback JSF is able to retrieve the exact same view scoped beans again by means of this parameter. So for a form that is first rendered, and then posted back once, 1 view scoped bean will be created.

For a datatable you will almost always want to use the view scope. The reason is that you want the data to be the same before and after a postback. If your data is 100% static and/or you don't have postbacks (your table is not in a form), you can use the request scope instead.

于 2012-11-26T17:15:36.273 回答