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

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.

主站蜘蛛池模板: 来凤县| 周口市| 廊坊市| 大同市| 南靖县| 即墨市| 察隅县| 江华| 平阴县| 莆田市| 巧家县| 宝坻区| 太仓市| 互助| 河间市| 台北市| 阿拉尔市| 萨嘎县| 通许县| 长丰县| 苏尼特右旗| 偏关县| 社旗县| 三门峡市| 上虞市| 全南县| 吴川市| 营口市| 灵石县| 南雄市| 城步| 萍乡市| 昌都县| 延吉市| 固原市| 鸡泽县| 玛曲县| 边坝县| 尉氏县| 乌拉特中旗| 皮山县|