Under /src/main, create a Source Folder called 'java'
(R-click on /src/main, select New-->Other, then select Java-->Source Folder)
In /src/main/java, create a class HelloBean.java in a package org.confucius
(R-click on /src/main/java, select New-->Other, then select Java-->Class)
The class looks like this:
package org.confucius;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name="helloBean")
@SessionScoped
public class HelloBean {
private String greeting;
public HelloBean(){
this.greeting = "Hello World JSF!";
}
public String getGreeting() {
return this.greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
Note the annotations that declare this class to be a JSF Bean named "helloBean".
We will describe annotations in detail in an upcoming post. For now, note that annotations are like inline-configurations. Any framework can define its unique set of annotations. For the Java compiler, the annotations are like comments - it more or less ignores them. But it lets the framework know of the annotations and the framework can take whatever action it needs to take. In this case, JSF framework will look at the annotations and create a bean with the name 'helloBean' and make it session-scoped.
This bean is Session-scoped which means that its state will be maintained for the duration of the HTTP session.
We can now access the methods of this Bean from our XHTMLs.
Update greet.xhtml like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h1>#{helloBean.greeting}</h1>
</h:body>
</html>
This style of using #{expression} for calling a Bean's method is called JSF EL (Expression Language).
Facelets view handler will do the needful to convert the EL expression to appropriate content.
If you rebuild and deploy HelloWorldJSF and point your browser to:
http://localhost:8080/HelloWorldJSF/
You will see "Hello World, JSF!" displayed.
No comments:
Post a Comment