官术网_书友最值得收藏!

Named beans

There are two types of Java Beans that can interact with JSF pages: JSF managed beans and CDI named beans. JSF managed beans have been around since the first version of the JSF specification and can be used only in a JSF context. CDI named beans were introduced in Java EE 6 and can interoperate with other Java EE APIs, such as Enterprise JavaBeans. For this reason, CDI named beans are preferred over JSF managed beans.

To make a Java class a CDI named bean, all we need to do is make sure the class has a public, no argument constructor (one is created implicitly if there are no other constructors declared, which is the case in our example) and add the @Named annotation at the class level. Here is the managed bean for our example:

package net.ensode.glassfishbook.jsf;
import javax.enterprise.context.RequestScoped; import javax.inject.Named; @Named @RequestScoped public class Customer { private String firstName; private String lastName; private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }

The @Named class annotation designates this bean as a CDI named bean. This annotation has an optional value attribute we can use to give our bean a logical name for use in our JSF pages. However, by convention, the value of this attribute is the same as the class name (Customer, in our case), with its first character switched to lower case. In our example, we let this default behavior take place, therefore we access our bean's properties via the customer logical name. Notice the value attribute of any of the input fields in our example page to see this logical name in action.

Notice that, other than the @Named and @RequestScoped annotations, there is nothing special about this bean. It is a standard JavaBean with private properties and corresponding getter and setter methods. The @RequestScoped annotation specifies that the bean should live through a single request. The different named bean, scopes, available for our JSF applications, are covered in the next section.

主站蜘蛛池模板: 峡江县| 开封市| 固始县| 长乐市| 庆安县| 绥德县| 宝丰县| 阿巴嘎旗| 酒泉市| 平度市| 黄平县| 巢湖市| 邯郸市| 册亨县| 榆树市| 三河市| 兴隆县| 巧家县| 临汾市| 禄丰县| 阳高县| 双城市| 荥阳市| 黎川县| 阳谷县| 织金县| 沙雅县| 乌恰县| 察隅县| 沙河市| 华坪县| 会泽县| 江北区| 巴彦县| 墨竹工卡县| 精河县| 上杭县| 黄梅县| 三门县| 女性| 封丘县|