Monday, February 7, 2011

Advance JSF

Hey ...

We are going to continue our tour in JSF. In previous post, we discuss about JSF phases and how it works. In this post we are going to continue in more configurations and JSF view tags.
We commence with faces-config.xml. Here is a simple configuration of 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_1_2.xsd"
              version="1.2">
    <managed-bean>
        <managed-bean-name>testForm</managed-bean-name>
        <managed-bean-class>com.test.TestForm</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <managed-bean>
        <managed-bean-name>studentForm</managed-bean-name>
        <managed-bean-class>com.student.StudentForm</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
            <from-outcome>show message</from-outcome>
            <to-view-id>/displayinfo.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

    <navigation-rule>
        <from-view-id>/displayinfo.jsp</from-view-id>
        <navigation-case>
            <from-outcome>back info</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
            <redirect/>
        </navigation-case>
    </navigation-rule>

    <navigation-rule>
        <navigation-case>
            <from-outcome>update student</from-outcome>
            <to-view-id>/student/studentView.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>student list</from-outcome>
            <to-view-id>/student/studentlist.jsp</to-view-id>
            <redirect/>
        </navigation-case>
        <navigation-case>
            <from-outcome>back</from-outcome>
            <to-view-id>/student/studentlist.jsp</to-view-id>
            <redirect/>
        </navigation-case>
    </navigation-rule>

    <lifecycle>
        <phase-listener>com.student.StudentPhaseTracker</phase-listener>
    </lifecycle>
</faces-config>

In this configuration we have 2 managed beans:
  • testForm
  • studentForm
In managed-bean tag, we can specify our form bean which provides JSPs data and handle page event in server side. We should specify managed-bean-name and managed-bean-class like above samples. In managed-bean-scope we should specify the scope of managed-bean. It could be one of these:
  • application
  • none
  • request
  • session
These are the scope that we can access the managed-beans and their lifecycle will be determined on this way.
navigation-rule tag is the tag which we can handle our navigations between pages via this. There are some body tags for it.
  • from-view-id: we can specify from which JSP we can have specified navigation. It is not required but if you do not specify it, it means for any JSP you handle subsequent navigation.
  • navigation-case: you can determine your navigation by this required tag.
    • from-outcome: here you put the action which is returned by action method in managed-bean.
    • to-view-id: here you put the JSP address to be forwarded or redirected to it. The default is forward.
    • redirect: if you want to redirect to the specified JSP you can use this tag.
1. example 1
In this sample I had specified “show message” action which is raised from “index.jsp” to forward to “displayinfo.jsp” and “back info” action which is raised from “displayinfo.jsp” to redirect to “index.jsp”.
 There are these two fields “firstName” and “lastName” in testForm which is bind from “index.jsp” via “<h:inputText id="firstName" value="#{testForm.firstName}"/>” and “<h:outputLabel for="lastName" value="lastname"/>” tags. There are some useful tags in “jsf/html” and “tomahawk” tag libraries. We are going to explain some of them in this post. In JSF expression language we should first determine the managed-bean name then specify their fields or method. For input tags such as “inputText”, “selectOneMenu”, … in value field of the tag we can use this expression language. But in “commandButton”, “commandLink” and … for “action” and “actionListener” fields we use JSF expression language and we should also specify a method name of the managed-bean for them. These are a small list of usefull jsf html input and output tag:
JSF TagHTML rendered tag
h:outputTextspan
h:inputTextinput type="text"
h:selectOneMenuselect
h:outputLabellabel
h:commandButtoninput type="submit'
h:commandLinka
In the first sample we get user info in the first page and display them in second page:
first page

second page
In “display” button we call “testForm.showMessage” method. In “showMessage” method we add a message by “FacesContext.getCurrentInstance()”. “FacesContext.getCurrentInstance()” is a useful object that you can add message to it then you can display it via “<h:messages/>” tag. Consider that this message will be added to request scope. So you cannot have that in redirect mod.
“FacesContext.getCurrentInstance().addMessage” has two parameter:
  1. message name: It should be "formname:messagename". It is used for "<h:message for="messagename"/>" tag.
  2. FacesMessage Object: we can create this object any time it is needed. the constructor has 3 parameters: severity(for example FacesMessage.SEVERITY_ERROR), summery, detail.
we can have session, request, response and other useful HttpServlet objects in "FacesContext.getCurrentInstance().getExternalContext()" form example "(HttpSession) event.getFacesContext().getExternalContext().getSession(true)".
2. example 2
In this example we show you a simple crud. The entity is Student. the class diagram is:
communication diagram is:
list page
add and update page
In "faces-config.xml" file we define "phase-listener" to initiate student list. Because I don't use any DBMS so I fill a fix list of Student in session. I do that in "phase-listener". In "phase-listener" tag we should specify a class which implements "PhaseListener" interface. I do this via "StudentPhaseTracker". The class should implements 3 methods:
  • afterPhase: After JSF phase is raised.
  • beforePhase: Before JSF phase is raised.
  • getPhaseId: In this method we should specify in which phases "afterPhase" and "beforePhase" should be raised. we can return "PhaseId.ANY_PHASE" to raise after and before any phases.
I raise method in "PhaseId.RESTORE_VIEW".
In "studentlist.jsp" I used "<h:dataTable>" which should be explained more. "<h:dataTable>" renders dynamic list from a java list that should be specified in value field. We specify record variable in "var" field just like "c:foreach" JSTL tag. In "<h:column>" tag we specify records columns. In "<f:facet>" tag we specify columns header or footer by name field. for example "<f:facet name="header"><t:outputText value="level"/> </f:facet>". In "<h:column>" tag we can use any other JSF tags like "<h:outputText value="#{st.level == 1 ? 'B.S.' : 'M.S.'}"/>".
Other important points about "commandLink" and "commandButton" is the "immediate" field. If we set this to true, these command buttons bypass validation phase. Else validation is checked. It has two fields to invoke server side method.
  • action: The method should return string without any method parameters.
  • actionListener: This method is called sooner than action method. This method should be void and has one parameter: "ActionEvent" for example: " public void test(ActionEvent e){}".
Finally in "t:updateActionListener" tag we can set specific value into managed-beans fields whenever the action is raised. It has two fields:
  • property: The property name which should be set.
  • value: The value which is set.
for example:


<h:commandLink immediate="true" actionListener="" onclick="return confirm('delete this row?');" action="#{studentForm.deleteStudent}" value="delete">
                    <t:updateActionListener property="#{studentForm.student.id}" value="#{st.id}"/>
</h:commandLink>
here you can download the source code. After deploying into your application server (like tomcat), the url of example 1 is: "http://localhost:8080/index.jsf" and example 2 is: "http://localhost:8080/student/studentlist.jsf".

Enjoy yourselves ;)
all rights reserved by Mostafa Rastgar and prgassist weblog

3 comments:

Unknown said...

your blog is nice and useful; but it seems most of your addressee are persian and i think persian version of these tips would be more wanted !!
not farsi blog but farsi version of content;
Good Luck pal;

mostafa rastgar said...

first: you mean i should post Persian version of my posts in other web log?
second: I am not Persian one ;)!

Anonymous said...

hi buddy.this tutorial of JSF was very useful to me.enjoyed it.thank u:)