- Java EE 8 Application Development
- David R. Heffelfinger
- 371字
- 2021-07-02 22:05:01
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.
- Getting Started with React
- Mobile Application Development:JavaScript Frameworks
- Hyper-V 2016 Best Practices
- 計(jì)算機(jī)圖形學(xué)編程(使用OpenGL和C++)(第2版)
- Oracle Database In-Memory(架構(gòu)與實(shí)踐)
- 跟老齊學(xué)Python:輕松入門
- 人人都是網(wǎng)站分析師:從分析師的視角理解網(wǎng)站和解讀數(shù)據(jù)
- Visual C++開發(fā)入行真功夫
- 編程菜鳥學(xué)Python數(shù)據(jù)分析
- Mastering Unity 2D Game Development(Second Edition)
- Swift 4 Protocol-Oriented Programming(Third Edition)
- Raspberry Pi Robotic Projects(Third Edition)
- Building Slack Bots
- 物聯(lián)網(wǎng)系統(tǒng)架構(gòu)設(shè)計(jì)與邊緣計(jì)算(原書第2版)
- 黑莓(BlackBerry)開發(fā)從入門到精通