Friday, 25 March 2016

JSF-2

JSF - Managed Beans

  • Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a java bean managed by JSF framework.
  • The managed bean contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).
  • Managed beans works as Model for UI component.
  • Managed Bean can be accessed from JSF page.
  • In JSF 1.2,a managed bean had to register it in JSF configuration file such as faces-config.xml.
  • From JSF 2.0 onwards, Managed beans can be easily registered using annotations. This approach keeps beans and there registration at one place and it becomes easier to manage.

Using XML Configuration

<managed-bean>
  <managed-bean-name>helloWorld</managed-bean-name>
  <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
</managed-bean> 
<managed-bean>
  <managed-bean-name>message</managed-bean-name>
  <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
</managed-bean> 

Using Annotation

@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
 
   @ManagedProperty(value="#{message}")
   private Message message;
   ...
}

@ManagedBean Annotation

@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case it would be helloWorld.
Another important attribute is eager. If eager="true" then managed bean is created before it is requested for the first time otherwise "lazy" initialization is used in which bean will be created only when it is requested.

Scope Annotations

Scope annotations set the scope into which the managed bean will be placed. If scope is not specified then bean will default to request scope. Each scope is briefly discussed below
ScopeDescription
@RequestScopedBean lives as long as the HTTP request-response lives. It get created upon a HTTP request and get destroyed when the HTTP response associated with the HTTP request is finished.
@NoneScopedBean lives as long as a single EL evaluation. It get created upon an EL evaluation and get destroyed immediately after the EL evaluation.
@ViewScopedBean lives as long as user is interacting with the same JSF view in the browser window/tab. It get created upon a HTTP request and get destroyed once user postback to a different view.
@SessionScopedBean lives as long as the HTTP session lives. It get created upon the first HTTP request involving this bean in the session and get destroyed when the HTTP session is invalidated.
@ApplicationScopedBean lives as long as the web application lives. It get created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and get destroyed when the web application shuts down.
@CustomScopedBean lives as long as the bean's entry in the custom Map which is created for this scope lives.

@ManagedProperty Annotation

JSF is a simple static Dependency Injection(DI) framework.Using @ManagedProperty annotation a managed bean's property can be injected in another managed bean.

Example Application

Let us create a test JSF application to test the above annotations for managed beans.
StepDescription
1Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - Create Application chapter.
2Modify HelloWorld.java as explained below. Keep rest of the files unchanged.
3Create Message.java under a package com.tutorialspoint.test as explained below.
4Compile and run the application to make sure business logic is working as per the requirements.
5Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver.
6Launch your web application using appropriate URL as explained below in the last step.

HelloWorld.java

package com.tutorialspoint.test;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {

   @ManagedProperty(value="#{message}")
   private Message messageBean;

   private String message;

   public HelloWorld() {
      System.out.println("HelloWorld started!");   
   }
   public String getMessage() {
      if(messageBean != null){
         message = messageBean.getMessage();
      }       
      return message;
   }
   public void setMessageBean(Message message) {
      this.messageBean = message;
   }
}

Message.java

package com.tutorialspoint.test;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "message", eager = true)
@RequestScoped
public class Message {
 
 private String message = "Hello World!";
 
 public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

home.xhtml

<!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">
<head>
   <title>JSF Tutorial!</title>
</head>
<body>
   #{helloWorld.message}
</body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce following result:
JSF Managed Beans

JSF - Page Navigation

Navigation rules are those rules provided by JSF Framework which describe which view is to be shown when a button or link is clicked.
  • Navigation rules can be defined in JSF configuration file named faces-config.xml.
  • Navigation rules can be defined in managed beans.
  • Navigation rules can contain conditions based on which resulted view can be shown.
  • JSF 2.0 provides implicit navigation as well in which there is no need to define navigation rules as such.

Implicit Navigation

JSF 2.0 provides auto view page resolver mechanism named implicit navigation.In this case you only need to put view name in action attribute and JSF will search the correct view page automatically in the deployed application.
JSF Home Page

Auto navigation in JSF page

Set view name in action attribute of any JSF UI Component.
<h:form>
   <h3>Using JSF outcome</h3>
   <h:commandButton action="page2" value="Page2" />
</h:form>
Here when Page2 button is clicked, JSF will resolve the view name, page2 as page2.xhtml extension, and find the corresponding view file page2.xhtml in the current directory.
JSF Page 2

Auto navigation in Managed Bean

Define a method in managed bean to return a view name.
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
   public String moveToPage1(){
      return "page1";
   }
}
Get view name in action attribute of any JSF UI Component using managed bean.
<h:form>
   <h3>Using Managed Bean</h3>
   <h:commandButton action="#{navigationController.moveToPage1}"
   value="Page1" />
</h:form>
Here when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml extension, and find the corresponding view file page1.xhtml in the current directory.
JSF Page 1

Conditional Navigation

Using managed bean we can very easily control the navigation. Look at following code in a managed bean.
JSF Conditional Navigation
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {

   //this managed property will read value from request parameter pageId
   @ManagedProperty(value="#{param.pageId}")
   private String pageId;

   //condional navigation based on pageId
   //if pageId is 1 show page1.xhtml,
   //if pageId is 2 show page2.xhtml
   //else show home.xhtml
   public String showPage(){
      if(pageId == null){
         return "home";
      }
      if(pageId.equals("1")){
         return "page1";
      }else if(pageId.equals("2")){
         return "page2";
      }else{
         return "home";
      }
   }
}
Pass pageId as a request parameter in JSF UI Component.
<h:form>
   <h:commandLink action="#{navigationController.showPage}" value="Page1">
      <f:param name="pageId" value="1" />
   </h:commandLink>
   <h:commandLink action="#{navigationController.showPage}" value="Page2">
      <f:param name="pageId" value="2" />
   </h:commandLink>
   <h:commandLink action="#{navigationController.showPage}" value="Home">
      <f:param name="pageId" value="3" />
   </h:commandLink>
</h:form>
Here when "Page1" button is clicked
  • JSF will create a request with parameter pageId=1
  • Then JSF will pass this parameter to managed property pageId of navigationController
  • Now navigationController.showPage() is called which will return view as page1 after checking the pageId
  • JSF will resolve the view name, page1 as page1.xhtml extension
  • and find the corresponding view file page1.xhtml in the current directory
JSF Page 1

Resolving Navigation based on from-action

JSF provides navigation resolution option even if managed bean different methods returns same view name.
JSF From Action Look at following code in a managed bean.
public String processPage1(){
   return "page";
}
public String processPage2(){
   return "page";
}
To resolve views, define following navigation rule in faces-config.xml
<navigation-rule>
   <from-view-id>home.xhtml</from-view-id>
   <navigation-case>
      <from-action>#{navigationController.processPage1}</from-action>
      <from-outcome>page</from-outcome>
      <to-view-id>page1.jsf</to-view-id>
   </navigation-case>
   <navigation-case>
      <from-action>#{navigationController.processPage2}</from-action>
      <from-outcome>page</from-outcome>
      <to-view-id>page2.jsf</to-view-id>
   </navigation-case>
</navigation-rule>
Here when Page1 button is clicked
  • navigationController.processPage1() is called which will return view as page
  • JSF will resolve the view name, page1 as view name is page and from-action in faces-config is navigationController.processPage1
  • and find the corresponding view file page1.xhtml in the current directory
JSF Page 1

Forward vs Redirect

JSF by default performs a server page forward while navigating to another page and the URL of the application do not changes.
To enable the page redirection, append faces-redirect=true at the end of the view name.
JSF Forward vs Redirect
<h:form>
   <h3>Forward</h3>
   <h:commandButton action="page1" value="Page1" />
   <h3>Redirect</h3>
   <h:commandButton action="page1?faces-redirect=true" value="Page1" />
</h:form>
Here when Page1 button under Forward is clicked
JSF Page 1 Forward Here when Page1 button under Redirect is clicked
JSF Page 1 Redirect

Example Application

Let us create a test JSF application to test all of the above navigation examples.
StepDescription
1Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - Create Application chapter.
2Create NavigationController.java under a package com.tutorialspoint.test as explained below.
3Create faces-config.xml under a WEB-INF folder and updated its contents as explained below.
4Update web.xml under a WEB-INF folder as explained below.
5Create page1.xhtml and page2.xhtml and modify home.xhtml under a webapp folder as explained below.
6Compile and run the application to make sure business logic is working as per the requirements.
7Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver.
8Launch your web application using appropriate URL as explained below in the last step.

NavigationController.java

package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {

   private static final long serialVersionUID = 1L;

   @ManagedProperty(value="#{param.pageId}")
   private String pageId;

   public String moveToPage1(){
      return "page1";
   }

   public String moveToPage2(){
      return "page2";
   }

   public String moveToHomePage(){
      return "home";
   }

   public String processPage1(){
      return "page";
   }

   public String processPage2(){
      return "page";
   }

   public String showPage(){
      if(pageId == null){
         return "home";
      }
      if(pageId.equals("1")){
         return "page1";
      }else if(pageId.equals("2")){
         return "page2";
      }else{
         return "home";
      }
   }

   public String getPageId() {
      return pageId;
   }

   public void setPageId(String pageId) {
      this.pageId = pageId;
   }
}

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
   version="2.0">
   <navigation-rule>
      <from-view-id>home.xhtml</from-view-id>
      <navigation-case>
         <from-action>#{navigationController.processPage1}</from-action>
         <from-outcome>page</from-outcome>
         <to-view-id>page1.jsf</to-view-id>
      </navigation-case>
      <navigation-case>
         <from-action>#{navigationController.processPage2}</from-action>
         <from-outcome>page</from-outcome>
         <to-view-id>page2.jsf</to-view-id>
      </navigation-case>
   </navigation-rule>
</faces-config>

web.xml

<!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd" >

   <web-app>
   <display-name>Archetype Created Web Application</display-name>

   <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Development</param-value>
   </context-param>
   <context-param>
      <param-name>javax.faces.CONFIG_FILES</param-name>
      <param-value>/WEB-INF/faces-config.xml</param-value>
   </context-param>
   <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.jsf</url-pattern>
   </servlet-mapping>
</web-app>

page1.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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">
   <h:body>
      <h2>This is Page1</h2>
      <h:form>
         <h:commandButton action="home?faces-redirect=true"
            value="Back To Home Page" />
      </h:form>
   </h:body>
</html>

page2.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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">
   <h:body>
      <h2>This is Page2</h2>
      <h:form>
         <h:commandButton action="home?faces-redirect=true"
            value="Back To Home Page" />
      </h:form>
   </h:body>
</html>

home.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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:f="http://java.sun.com/jsf/core"
   xmlns:h="http://java.sun.com/jsf/html">

   <h:body>
      <h2>Implicit Navigation</h2>
      <hr />
      <h:form>
         <h3>Using Managed Bean</h3>
         <h:commandButton action="#{navigationController.moveToPage1}"
            value="Page1" />
         <h3>Using JSF outcome</h3>
         <h:commandButton action="page2" value="Page2" />
      </h:form>
      <br/>
      <h2>Conditional Navigation</h2>
      <hr />
      <h:form>
         <h:commandLink action="#{navigationController.showPage}"
            value="Page1">
            <f:param name="pageId" value="1" />
         </h:commandLink>
              
         <h:commandLink action="#{navigationController.showPage}"
            value="Page2">
            <f:param name="pageId" value="2" />
         </h:commandLink>
              
         <h:commandLink action="#{navigationController.showPage}"
            value="Home">
            <f:param name="pageId" value="3" />
         </h:commandLink>
      </h:form>
      <br/>
      <h2>"From Action" Navigation</h2>
      <hr />
      <h:form>
         <h:commandLink action="#{navigationController.processPage1}"
         value="Page1" />
              
         <h:commandLink action="#{navigationController.processPage2}"
         value="Page2" />
              
      </h:form>
      <br/>
      <h2>Forward vs Redirection Navigation</h2>
      <hr />
      <h:form>
         <h3>Forward</h3>
         <h:commandButton action="page1" value="Page1" />
         <h3>Redirect</h3>
         <h:commandButton action="page1?faces-redirect=true"
         value="Page1" />
      </h:form>
   </h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce following result:
JSF Navigation

 

JSF - Basic Tags

Basic JSF Tags

JSF provides a standard HTML tag library. These tags get rendered into corresponding html output.
For these tags you need to use the following namespaces of URI in html node.

<html 
   xmlns="http://www.w3.org/1999/xhtml" 
   xmlns:h="http://java.sun.com/jsf/html" 
>
Following are important Basic Tags in JSF 2.0:
S.N. Tag & Description
1 h:inputText
Renders a HTML input of type="text", text box.
2 h:inputSecret
Renders a HTML input of type="password", text box.
3 h:inputTextarea
Renders a HTML textarea field.
4 h:inputHidden
Renders a HTML input of type="hidden".
5 h:selectBooleanCheckbox
Renders a single HTML check box.
6 h:selectManyCheckbox
Renders a group of HTML check boxes.
7 h:selectOneRadio
Renders a single HTML radio button.
8 h:selectOneListbox
Renders a HTML single list box.
9 h:selectManyListbox
Renders a HTML multiple list box.
10 h:selectOneMenu
Renders a HTML combo box.
11 h:outputText
Renders a HTML text.
12 h:outputFormat
Renders a HTML text. It accepts parameters.
13 h:graphicImage
Renders an image.
14 h:outputStylesheet
Includes a CSS style sheet in HTML output.
15 h:outputScript
Includes a script in HTML output.
16 h:commandButton
Renders a HTML input of type="submit" button.
17 h:Link
Renders a HTML anchor.
18 h:commandLink
Renders a HTML anchor.
19 h:outputLink
Renders a HTML anchor.
20 h:panelGrid
Renders an HTML Table in form of grid.
21 h:message
Renders message for a JSF UI Component.
22 h:messages
Renders all message for JSF UI Components.
23 f:param
Pass parameters to JSF UI Component.
24 f:attribute
Pass attribute to a JSF UI Component.
25 f:setPropertyActionListener
Sets value of a managed bean's property

 

 

1 comment: