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

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.

主站蜘蛛池模板: 江油市| 建始县| 周口市| 忻城县| 丹巴县| 汉寿县| 甘孜县| 安吉县| 泊头市| 资阳市| 八宿县| 鄯善县| 石楼县| 广东省| 治县。| 成武县| 乌苏市| 芜湖市| 称多县| 新余市| 湟源县| 阿坝县| 牙克石市| 洮南市| 仲巴县| 高平市| 临朐县| 云梦县| 贺兰县| 红安县| 辰溪县| 大渡口区| 陇南市| 含山县| 西和县| 沙湾县| 潍坊市| 博乐市| 嘉定区| 江西省| 菏泽市|