Showing posts with label JSF. Show all posts
Showing posts with label JSF. Show all posts

Enable / Disable DatePicker of JSF in Portal

<h:inputText id="txtDate"  value="#{pc_MyBean.startDt}" >
    <f:convertDateTime pattern="dd-MM-yyyy" />
    <hx:inputHelperDatePicker firstDay="1" />
</h:inputText>

1) Enable this in portal
    document.getElementById('view'+'<portlet:namespace/>'+':frmName:txtDate').disabled = false;
    hX_5.getComponentById('view'+'<portlet:namespace/>'+':frmName:txtDate').redraw();

1) Disable this in portal
    document.getElementById('view'+'<portlet:namespace/>'+':frmName:txtDate').disabled = true;
    hX_5.getComponentById('view'+'<portlet:namespace/>'+':frmName:txtDate').redraw();
Click here to View more...

Integrating JSF and Spring

We’re currently using JSF and Spring together and I could say that integration of these two frameworks is not so hard thanks to the Springs facilities. I am using two different ways when I need to access the beans managed by spring. One is to use the delegating resolver and the other is to the FacesContextUtils

1) Delegating Resolver
For example you have a facade called FacadeService and it has a dependency to another service called “SomeService” which implements “ISomeService”. Also “SomeService” is managed by spring. The first is to define the FacadeService as;
package yourpackagename;
public class FacadeService {
private ISomeService someService;
public ISomeService getSomeService() {
return someService;
}
public void setSomeService(ISomeService someService) {
this.someService = someService;
}
}
The next step is to define this FacadeService as a managed bean in the faces-config.xml by; The other bean definition is a backing bean of your jsf page.
>facadeService
<managed-bean-class>
yourpackagename.FacadeService
</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<property-name>someService</property-name>
<property-class>
packagename.ISomeService
</property-class>
<value>#{someService}</value>
</managed-property>
</managed-bean>

>backingBeanName
<managed-bean-class>
yourpackagename.backingBeanClass
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>facadeService</property-name>
<property-class>
packagename.FacadeService
</property-class>
<value>#{facadeService}</value>
</managed-property>
</managed-bean>
* Also the delegating resolver must be defined in faces-config.xml between the application tag as following;
<application>
<
variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>;
<
/application>
* Next step is putting the listener of spring goes into the web.xml and telling the location of spring’s xml
<context-param>
<param-name>contextConfigLocation
/WEB-INF/applicationContext.xml
The place of applicationContext.xml is optional, you should also put it under classes and refer it like classpath:/applicationContext.xml.


org.springframework.web.context.ContextLoaderListener

* Here is the spring’s xml to manage the someService bean


“-//SPRING//DTD BEAN//EN”
“http://www.springframework.org/dtd/spring-beans.dtd”>
default-dependency-check=”none”>

* So thats all metadata you need to configure, the final step is to add the FacadeService to the code behind of your jsf page by simply adding this; For example you have a backing bean called YourBackingBean.java, Faces inject facadeService to this bean since we have configured it. Also the spring bean (some service) is injected via the delegation variable resolver when creating the facadeService.
public class YourBackingBean{
protected FacadeService facadeService;
public FacadeService getFacadeService() {

return facadeService;
}
public void setFacadeService(FacadeService facadeService) {
this.facadeService = facadeService;
}
}
There is an important note here, using the #{facadeService} you can get the value of the FacadeService managed by Faces, the default variable resolver of JSF will bring it for you. Also you can get the SomeService object by writing the appropriate accessor methods and replacing the value binding expression with #{someService}. The default variable resolver will not find “someService” and the responsibility will pass to the DelegatingVariableResolver of Spring which will return the someService name. Long story short, here comes the fun part, accessing the spring bean from code behind, for example at anywhere in your jsf code behind you can reach the spring bean by;
getFacadeService().getSomeService().someMethod(); //If everything is ok, hopefully no npe
These steps allows the JSF-Spring integration, inversion of control is applied both by spring and faces, facadeservice is managed by Faces and these are wired using the delegating variable resolver of spring. Important thing is spring bean is not injected by spring, the wiring is done by faces. Spring’s role is a container in this case.
2) Using the FacesContextUtils
I always see this one as the alternative and I dont use it unless I have to. For example, I have created a custom jsf component and a custom variable resolver. Both of these needed to use spring beans. So thats why I’ve reached spring directly. FacesContextUtils is an utility class that is located in spring framework.
ISomeService someService = (ISomeService) FacesContextUtils
.getWebApplicationContext(FacesContext.getCurrentInstance())
.getBean(“someService”);
someService.someMethod();
To sum up, I could say using these two frameworks is fun and spring’s mechanisms make it very easy.You can either use the delegating resolver or FacesContextUtils to use the beans managed by Spring and Faces together.
Click here to View more...

Ajax issue in jsf - data lost without saving

If there more then 4 Ajaxrefreshrequests on a given page, and then the user opts to save such data, the page refreshes without saving the data.
This is because of the com.sun.faces.numberOfViewsInSession exceeds and a new view is created...which can loose some of the data on the page

Solution to this problem :

In web.xml add this entry

    <context-param>
        <param-name>com.sun.faces.numberOfViewsInSession</param-name>
        <param-value>28</param-value>
    </context-param>
Click here to View more...

ENTER key closes hx:panelDialog issue

Issue with <hx:panelDialog> on ENTER key press the panelDialog closes,

Solution:
Add hx:behaviorKeyPress tag to suppress the Enter Key as follows

<hx:panelDialog type="modal" ...>
    <hx:behaviorKeyPress key="Enter" onActionFunction="return false">
</hx:panelDialog>
Click here to View more...

Fix column hx:columnEx in hx:dataTableEx of JSF

In this case tried a lot of things but this is possible just by using properties of CSS !

In Jsp :: var portletNamespace = '<portlet:namespace/>';


<h:panelGroup id="panelGroupId" layout="block" style="overflow: scroll; width:1020px;" rendered="#{not empty bean.instrumentList}">
<hx:dataTableEx border="0" cellpadding="0" cellspacing="0" rendered="true"
    columnClasses="columnClass1" headerClass="headerClass"
    footerClass="footerClass" rowClasses="rowClass1, rowClass2"
    styleClass="dataTableEx" id="tableEx1"
    value="#{bean.instrumentList}" var="dataItem"
    cellpadding="2"    cellspacing="0" width="100%">

<hx:columnEx id="columnEx12"                               
nowrap="true" align="center" width="80" style="background-color:#ede4da;POSITION:relative;
LEFT:expression(document.getElementById('view'+portletNamespace+':formName:panelGroupId').scrollLeft-1);Z-INDEX:1">

    <f:facet name="header">
        <h:outputText id="text1" styleClass="outputText" value="Field1"></h:outputText>
    </f:facet>
    <h:outputText style="border:none;" value="#{varInstrument.name}"/>
</hx:columnEx>

</hx:dataTableEx>
</h:panelGroup>
Click here to View more...

h:selectOneRadio in JSF

<h:selectOneRadio value="#{testBean.paymentBalance}"
layout="pageDirection" rendered="#{testBean.oneTimePaymentIncluded}">
<f:selectItems value="#{testBean.paymentAmounts}" />
</h:selectOneRadio>


public ArrayList<SelectItem> getPaymentAmounts() {
ArrayList<SelectItem> paymentAmounts = new ArrayList<SelectItem>();

SelectItem currentBalance = new SelectItem();
currentBalance.setLabel("CurrentBalance " + getWholePaymentBalance());
currentBalance.setValue("CurrentBalance");
paymentAmounts.add(currentBalance);

SelectItem lateBalance = new SelectItem();
lateBalance.setLabel("PastDueBalance " + getPastDueBalance());
lateBalance.setValue("PastDueBalance");
paymentAmounts.add(lateBalance);

SelectItem otherBalance = new SelectItem();
otherBalance.setLabel("OtherBalance");
otherBalance.setValue("OtherBalance");
paymentAmounts.add(otherBalance);

return paymentAmounts;
} Click here to View more...

JSF - FacesUtility Class (FasesUtil) part1

getFacesContext
 public static FacesContext getFacesContext(){
        return  FacesContext.getCurrentInstance();
    }
   
 

getRequestParameter
 public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get(name);
    } 


getApplication
public  static Application getApplication(FacesContext facesContext) {
        return facesContext.getApplication();       
    }


getManagedBean
 public static Object getManagedBean( String mgdBeanName,
            FacesContext facesContext) {
        String expression = "#{" + mgdBeanName + "}";
       
        return resolveExpression(expression, facesContext);                   
    }    


getBackingBean
public static Object getBackingBean( String backingBeanName,
            FacesContext facesContext) {
       
        return getManagedBean(backingBeanName, facesContext);                   
    }


getPortletSession
 public static PortletSession getPortletSession() {
        PortletRequest request = (PortletRequest) getFacesContext()
                .getExternalContext().getRequest();
        return request.getPortletSession();
    }
 

getPortletContext
    public static PortletContext getPortletContext(){       
        return (PortletContext)getFacesContext().
                                            getExternalContext().getContext();
    } 


getSessionMapValue
public static Object getSessionMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().
                                                    getSessionMap().get(key);
    }




getPortletContext

    public static PortletContext getPortletContext(){       
        return (PortletContext)getFacesContext().
                                            getExternalContext().getContext();
 

    }

getHttpServletRequest
    public static HttpServletRequest getHttpServletRequest(){
        return (HttpServletRequest)getFacesContext().
                                            getExternalContext().getRequest();
    } 
Click here to View more...

JSF - AlphaNumericValidator

public class AlphaNumericValidator implements Validator
{
public void validate(FacesContext facesContext, UIComponent uiComponent,
        Object obj)
        throws ValidatorException {
        String errorMsg = "ALPHA_NUMERIC_EXCEPTION";
        final String strContent = (String) obj;
      
        Integer charCount = 0;
       
        if (strContent != null && strContent.length() != 0) {
             for (Integer i = 0; i < strContent.length(); i = i + 1) {
                 if(Character.toLowerCase(strContent.charAt(i)) >= 'a'
                         && Character.toLowerCase(strContent.charAt(i)) <='z'){
                     charCount = charCount + 1;
                 }
             }
             if (charCount == 0) {
                 FacesMessage message = new FacesMessage();
                 message.setDetail(errorMsg);
                 throw new ValidatorException(message);
             }
 }
}
 
Click here to View more...

JSF - making the bean NULL

FacesContext.getCurrentInstance().getApplication().
createValueBinding( "#{pc_XXXXBean}").
setValue(FacesContext.getCurrentInstance(), null );
Click here to View more...

AutoComplete for JSF SelectOneMenu component



On the net you can navigate over the options of a comboBox according to the first letter of the content. If you handle the onKeyPress event of comboBox then you can support navigation for all of the characters of options in the comboBox. Now user can navigate through the options by pressing characters on the focused comboBox. Here is the way to do it.

You need two global variables to hold the time out and pressed keys.

var combo_text = "";
var combo_timeout_id = null;

The onKeyPress function.

function onComboBoxKeyPress(event)
{
      var e = event.srcElement;

      if (combo_timeout_id)
            window.clearTimeout(combo_timeout_id);
      combo_text += String.fromCharCode(event.keyCode);
      var index = find_closest_item_index(e, combo_text);
      event.returnValue = false;
      e.selectedIndex = index;
      combo_timeout_id = window.setTimeout("special_combo_timed_out()", 500);
}

This function returns the best matching result by comparing the user-typed characters to comboBox options' value.

function find_closest_item_index(e, combo_text)
{
      var opt = e.options;
      var max_match_index = 0;
      var max_match = 0;

      for (i = 0; i < opt.length; i++)
      {
            var match_count = matching_char_count(opt(i).text, combo_text);

            if (match_count > max_match)
            {
                  max_match = match_count;
                  max_match_index = i;
            }
      }
      return max_match_index;
}

To find the number of matching characters...

function matching_char_count(text, pattern)
{
      var i = 0;
      var len = pattern.length;

      if (text.length < pattern.length)
            len = text.length;
      while (i < len)
      {
            if (text.charAt(i) != pattern.charAt(i))
                  break;
            i++;
      }
      return i;
}

Time out value for the user tpyings (0.5 sec).

function special_combo_timed_out()
{
      combo_text = "";
      window.clearTimeout(combo_timeout_id);
}

To enable this property for all the JSF SelectOneMenu you should define the onKeyPress event for all comboBoxes. So you have to define your own MenuRenderer in the renderkit of your faces-config.xml.
Add the new renderer to the renderkit in the faces-config.xml

javax.faces.SelectOne
javax.faces.Menu
my.new.renderer.MenuRenderer

The MenuRenderer will be slightly different from com.sun.faces.renderkit.html_basic.MenuRenderer with the renderingScript method and onKeyPress changes. 

You should add onKeyPress script to HtmlSelectOneMenu in the rendering method.

if (((HtmlSelectOneMenu)uicomponent).getOnkeypress() == null)
            responsewriter.writeAttribute("onkeypress", (?onComboBoxKeyPress(event);?, null);
else
  (((HtmlSelectOneMenu)uicomponent).getOnkeypress() != null)
            responsewriter.writeAttribute("onkeypress", ((HtmlSelectOneMenu)uicomponent).getOnkeypress(), null);

Now the last thing to do is to render the script that includes all the scripting stuff that i gave above. The script include tag should only be rendered for once per page so we should define two global variables in the MenuRenderer class to handle this situation

 private static final String COMBO_SORT_SCRIPT_RENDERED = "comboautocomplete-script-rendered";

 private static final String COMBO_SORT_SCRIPT_VIEW_ID = "comboAutoComplete.js";

COMBO_SORT_SCRIPT_VIEW_ID specifies should be same as the .js file. Here is the renderScriptOnce method. You should invoke it at the encodeBegin method of the renderer.

private void renderScriptOnce(ResponseWriter writer, UIComponent component, FacesContext context) throws IOException
{      Map requestMap = context.getExternalContext().getRequestMap();
      Boolean scriptRendered = (Boolean) requestMap.get(COMBO_SORT_SCRIPT_RENDERED);
      if (scriptRendered == Boolean.TRUE) {
            return;
      }
      requestMap.put(COMBO_SORT_SCRIPT_RENDERED, Boolean.TRUE);
      writer.write("\n");

      writer.startElement("script", component);
      writer.writeAttribute("type", "text/javascript", null);
      String src = "scripts/" + COMBO_SORT_SCRIPT_VIEW_ID;
      writer.writeAttribute("src", src, null);
      writer.endElement("script");
      writer.write("\n");
}



Click here to View more...

Disabling non-numeric character input in HTMLInputText - JSF

Here is the code from the page.
<h:inputText id="aText">
      <f:convertNumber integerOnly="true"/>
</h:inputText>



     
Click here to View more...

DataList in JSP - reload the session data

Session scope: Once loaded the dataList will persist during the session and won't be garbaged after one request in the same session. If you want to reload the session data every view to get the most recent data, then do as follows:

public List getDataList() {
        if (FacesContext.getCurrentInstance().getRenderResponse()) {
            loadDataList(); // Reload to get most recent data.
        }
        return dataList;
    }



The FacesContext#getRenderResponse() returns true when this getter is invoked during the render response phase. This is to prevent duplicate reloads as this getter can also be invoked during the apply request values phase or the process validations phase.


You can also consider to use two beans: one request-scoped bean for the views and form actions and one session-scoped bean for the session data. You can inject the session scoped bean in the request scoped bean as managed property using faces-config.xml. And in the request scoped bean you can invoke reload of the data after save/update/delete action of the session data.
Storing the data in the session scope has not only an impact on the server memory usage, but also on the user experience when the data is not for display only. Imagine what would happen with the data when the user manages (edit/delete) the data in multiple browser windows/tabs in the same session.
Instead of using the session scope you can also consider using the Tomahawk t:dataTable component. It has an extra attribute 'preserveDataModel' which you should set to true. This will store the datatable value in the component tree state in session and restore it during the next request. This way you can also avoid unforeseen concurrent updates on the datamodel in between the requests.
Click here to View more...

JSF application error running on WAS v7.0

Problem
WAS 7.0 is a JEE 5 container which is defined to contain a JSF 1.2 framework implementation. This implementation cannot be overridden by an application. If a web application contains a JSF implementation a runtime error similar to the following may appear:


RESULT: HTTP 500 error in internal web browser and Console view shows
[8/21/08 11:40:35:390 PDT] 0000003a servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet /index.jsp in application TestEAR. Exception created : com.ibm.websphere.servlet.error.ServletErrorReport: com.ibm.ws.jsp.JspCoreException: Unable to convert string 'form' to class javax.el.ValueExpression for attribute styleClass: java.lang.IllegalArgumentException: Property Editor not registered with the PropertyEditorManager
Resolving the problem

If you run into this condition and wish for your application to run on WAS v7.0 then you should follow these steps:



1) Remove the classpath for jsf-api.jar and jsf-impl.jar via Java Build Path UI accessible from the Project Properties.
2) Delete the files jsf-api.jar and jsf-impl.jar from WEB-INF/lib folder.
3) Clean and rebuild the project
4) Remove the EAR containing the project from the Servers view.
5) Run the JSP page on server again.
IBM(R) Websphere(R) Application Server: The Complete ReferenceProgramming Portlets: An Introduction Using IBM WebSphere PortalIBM WebSphere DataPower SOA Appliance HandbookMastering IBM WebSphere Portal: Expert Guidance to Build and Deploy Portal ApplicationsPro (IBM) WebSphere Application Server 7 Internals
Click here to View more...

Using Ajax with JSF components



Adding Ajax to a JSF page is a four-step process:

  1. Identify the area of the page that will be updated by the Ajax request. In Rational Application Developer V7, you can use Ajax with the content of almost any panel component. The panels range from simple containers, such as and , to feature-rich panels, such as menus () and dialogs ().
  2. Select the type of Ajax request to use. There are three different kinds of Ajax requests supported in the Rational Application Developer V7 JSF library:



    • GET request for the same page ()
    • POST request for the same page ()
    • GET request for another page ()
  3. Configure parameters to pass to the server with the Ajax request.



    • For GET requests, you can pass values of various input fields on the page.
    • For POST request, the entire form is submitted.
  4. Identify the event that initiates the Ajax request. This can be any client-side JavaScript event, such as onclick for a button, onblur for an input field, or onchange for a check box.
Let's walk through all of these steps, using a simple example of a "Hello, world" type of application. You'll build a page with two fields: input and output. After the user tabs out of the input field, you'll use Ajax to send the value that the user entered to the server and to update the output field with a greeting.
Set up your Web project
To begin, create a Web project (see Figure 1):
  • Select File > New > Project > Dynamic Web Project from the menu.
  • In the New Project wizard:
    1. Enter a project name (for example, HelloWorld).
    2. Select the Faces Project configuration.
    3. Select Add project to an EAR.
  • Click Finish.

Figure 1. New Dynamic Web Project screen
Figure 1. New Dynamic Web Project screen display

To create a Web page (see Figure 2):

  • Right-click the project name in the Project Explorer.
  • Select New > Web Page from the context menu.
  • In the New Web Page wizard, enter a page name (for example, hello).
  • Click Finish.

Figure 2. New Web Page wizard
Figure 2. New Web Page wizard

Add components to the page
Now that you have a page to work with, you'll add the components. You'll use an inputText component for the text field where the user will type a name and an outputText component to show the greeting. Because you're going to update the outputText with Ajax, you need to put it inside of a panel component. You'll use a panelGroup component for this page.
To add the components:

  • Drag an Input component from the Enhanced Faces Components drawer of the palette onto the page.
  • Drag a Panel Group box component from the palette onto the page below the Input component. When you are prompted for the group box type, select Group.
  • Drag an Output component from the palette onto the Panel Group box.
Add Ajax support to the panel
To make content of the panel updatable via Ajax (in this case, an Output field), you need to mark the panel as "Ajaxable" and configure the parameters that you want the user's request to pass to the server. (See Figure 3.)

  1. Select the outputText component and switch to the Properties view.
  2. In the Properties view, select the h:panelGroup tag, which is directly above the h:outputText tag in the left-side tag navigator.
  3. Select the Ajax page for the h:panelGroup tag.
  4. Click the Allow Ajax updates check box.
  5. Select Refresh as the Ajax request type.

Figure 3. panelGroup Properties
Figure 3. panelGroup Properties

This example uses a Refresh request to show how parameters can be passed with an Ajax request. Alternatively, a Submit request would submit the entire form. In that case, because the form on the sample page contains just one input field, you would not need to configure parameters for the Ajax request at all.
To configure parameters for the Ajax request (Figure 4):

  • Select Click to edit Ajax request properties on the Ajax properties page (see Figure 3, shown previously).
  • On the Properties page for the hx:ajaxRefreshRequest tag:



    1. Click Add Parameter for the parameters to send from the browser.
    2. Select the name of the Input component (in this case, text1) from the combo box.

Figure 4. ajaxRefreshRequest Properties
Figure 4. ajaxRefreshRequest Properties

You have configured the panelGroup tag to be updated by an Ajax request and to use the value of the Input field as a parameter for the request. The only thing left to do is to make the outputText component use this parameter to display a greeting (see Figure 5):

  • Select the outputText component.
  • Enter Hello, #{param.text1} into the Value field.

Figure 5. outputText Properties
Figure 5. outputText Properties

Initiate the Ajax request
If you look back to the four steps required to use Ajax, you will see that you have already completed the first three steps. Now you just need to identify the event that will trigger the Ajax request. To update the greeting as soon as the user tabs out of the input field, you'll use the onblur event on the inputText component (see Figure 6):

  • Select the inputText component.
  • Switch to Quick Edit view.
  • In the Quick Edit view:



    1. Select the onblur event in the list of events on the left side.
    2. Click the Use predefined behavior check box.
    3. Select the Invoke Ajax behavior on the specified tag action.
    4. Select the name of the panelGroup (in this case, group1) as the target.

Figure 6. Quick Edit view
Figure 6. Quick Edit view

Now you can save the page and run it on a server. When the browser window opens, you will see an input field and the "Hello" text beneath it. As soon as the user types anything in the field and then tabs out, the greeting will be updated with the text that the user typed in the input field. (See Figure 7.)

Figure 7. Run the Web page on the server
Figure 7. Run the Web page on the server

As you can see, you were able to build a simple yet functional Ajax page with standard JSF components and absolutely no JavaScript code.

Click here to View more...

Creating custom JSF parent component

You may wish to create a JSF component that can contain other child JSF components.
Words are very nice but how to implement this idea ???
Assume we want to create a component that can hide and show the child components based upon a specific attribute. Let call our component (parentTag) and the attribute (visible).
For example)
<c:parentTag visible="#{myBean.visible}">
<h:commandButton .../>
<h:inputText .../>
<!--Other JSF components here-->
</c:parentTag>
If #{myBean.visible} is true then the child components will be visible else they won't appear.

The main trick is here at the Renderer class using the
getRendersChildren( ) and encodeChildren( ) methods.

Let's see how to make this ...
//The main trick is here at the Renderer class ...
class ParentTagRenderer extends Renderer {
//Must override this method to tell that you are a parent component ...
public boolean getRendersChildren() {
return true;
}

//Here is the method that is responsible for rendering the child components ...
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException {
String visible = (String) component.getAttributes().get("visible");
//If the value is true then render the childrens ...
if ("true".equalsIgnoreCase(visible)) {
super.encodeChildren(context, component);
}
}
/*Other Renderers methods ...*/
}
Click here to View more...

Overriding The JSF Renderers

Override the JSF component renderers needs just to do the following:
1. Create the Renderer class.
2. Register the Renderer class in the faces-config.xml.
In the example, I will make the simple scenario. It is extending the JSF Label component (Assume that you want to make your JSF labels start with *).
Following the described steps above
1. Create the Renderer class :


2. Register the Renderer class in the faces-config.xml.

3. Write the test JSP page.

4. This is the output.


I hope that this post is useful.




Click here to View more...

Using Tiles in JSF Applications

This short downloadable example project demonstrates how you can use JSF with Tiles. This is the URL:

http://webdownload.exadel.com/getfiles/jsf/examples/jsf-tiles.war (2.14M)

Then, all you have to do is add the struts.jar file from the Struts 1.1 distribution to your classpath. Including struts.jar does not mean that Struts itself is required to use JSF with Tiles. It's just that the Tiles packages are distributed inside the struts.jar file. No other functionality of the Struts Framework is involved.




Some Useful Tips

1. Here is the snippet from the web.xml file that enables Tiles:
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>TilesServet</servlet-name>
<servlet-class>org.apache.struts.tiles.TilesServlet</servlet-class>
<init-param>
<param-name>definitions-config</param-name>
<param-value>/WEB-INF/tiles-defs.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

Pay attention to the load-on-startup tag. The Tiles Servlet should be loaded after the Faces Servlet. This is important!

2. tiles-defs.xml is the standard name for a Tiles definitions file. However, you can call it anything you want and you can use more than one file. Use a comma-separated string to define such files for the definitions-config parameter in the web.xml file.

3. Use flush="false" for the tiles:insert tag is you use it inside an f:view element (between opening and closing f:view tags).

4. Use f:subview if you use tiles inside an f:facet element. For example:
<f:facet name="header">
<f:subview id="header">
<tiles:insert definition="page.header" flush="false"/>
</f:subview>
</f:facet>
5. Never include an f:view element inside another f:view element.

6. You cannot forward directly to the tiles, like in Struts. So, the JSF faces-config file should reference the pages using tiles as views.

7. Follow this online documentation: http://www.lifl.fr/~dumoulin/tiles/

8. For Exadel JSF Studio users, the jsf-tiles example is also available as a Exadel Studio project: http://webdownload.exadel.com/getfiles/jsf/examples/jsf-tiles.zip. Unzip it and import (File/Import/JSF Project) it into your Exadel Studio workspace.








Click here to View more...

Auto Focus on particular element on page load in JSF

Inside <f:view> place the following scriplet..

<%
javax.faces.context.FacesContext.getCurrentInstance()
.getViewRoot().setLocale(request.getLocale());
%>

-------------------------------------------------------------
Above </h:form> plce the following code...
The target filed (XXXX) indicates which field should have focus on page load

<hx:inputHelperSetFocus id="setFocus1" target="XXXX"
rendered="true"></hx:inputHelperSetFocus>


Click here to View more...

Problems related with ValueChangeListeners in JSF

Ok now I never quite figured this one out. The idea behind value change listeners should be simple. However EVERYONE gets confused because they don’t execute when expected.


Ok what you might of missed! Value change listeners are fired before the Setter methods are called.

So what?

Well this means any changes you make to variables from your value change method will be overwritten when the setters are called.


So I commonly hear just call FacesContext.getCurrentInstace.renderResponse()

so this should skip the phases meaning the setters are not called and go directly to the render response phase.

At first glance yes perfect it works.

What it doesn't do is update the VIEW ?
The getters are never called on your managed bean properties which means that the view is never updated with the values you change from you valueChangeListener.

How annoying :) so how to get around this.


1) You can force JSF to recreate the view.

Make a navigation rule to navigate back to the same page and call it in your value change method.

FacesContext.getCurrentInstance().getApplication().getNavigationHandler().
handleNavigation(FacesContext.getCurrentInstance(),null,"test");

< navigation-rule >
< from-view-id > /myPage.jsp< /from-view-id >
< navigation-case >
< from-outcome > test< /from-outcome >
< to-view-id > / myPage.jsp< /to-view-id >
< /navigation-case >
< /navigation-rule >

2) Move the value change event to the update model phase.

This way your setters are called before your value change event something like

public void changeMethod(ValueChangeEvent event)
{
PhaseId phaseId = event.getPhaseId();
String oldValue = (String) event.getOldValue();
String newValue = (String) event.getNewValue();
if (phaseId.equals(PhaseId.ANY_PHASE))
{
event.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
event.queue();
}
else if (phaseId.equals(PhaseId.UPDATE_MODEL_VALUES))
{
// do you method here
}
}

3) Create your UICcomponents in your bean (use binding) and from your value change method call the .setMethod() on the UIComponents, then call the FacesContext.getCurrentInstance().renderResponse();
It appears the getters are called if you update the UI components directly.




I know these seems like hacks but for now I have not found any better solutions to what really seems like a flaw in the design

Click here to View more...

JSF Tag Library

Table of JSF Core Tags

Tag Description
f:view Creates the top-level view
f:subview Creates a subview of a view
f:facet Adds a facet to a component
f:attribute Adds an attribute (key/value) to a component
f:param Constructs a parameter component
f:actionListener Adds an action listener to a component
f:valueChangeListener Adds a valuechange listener to a component
f:setPropertyChangeListener (JSF 1.2) Adds an action listener to a component that sets a bean property to a given value.
f:converter Adds an arbitrary converter to a component
f:convertDateTime Adds a datetime converter to a component
f:convertNumber Adds a number converter to a component
f:validator Adds a validator to a component
f:validateDoubleRange Validates a double range for a component’s value
f:validateLength Validates the length of a component’s value
f:validateLongRange Validates a long range for a component’s value
f:loadBundle Loads a resource bundle, stores properties as a Map
f:selectitems Specifies items for a select one or select many component
f:selectitem Specifies an item for a select one or select many component
f:verbatim Adds markup to a JSF page

Table 4–3 JSF HTML Tags

Tag Description
h:form HTML form
h:inputText Single-line text input control. Examples
h:inputTextArea Multiline text input control. Examples
h:inputSecret Password input control. Examples
h:inputHidden Hidden field
h:outputLabel Label for another component for accessibility
h:outputLink HTML anchor. Examples
h:outputFormat Like outputText, but formats compound messages
h:outputText Single-line text output. Examples
h:commandButton Button: submit, reset, or pushbutton. Examples
h:commandLink Link that acts like a pushbutton. Examples
h:message Displays the most recent message for a component
h:messages Displays all messages
h:grapicImage Displays an image. Examples
h:selectOneListbox Single-select listbox. Examples
h:selectOneMenu Single-select menu. Examples
h:selectOneRadio Set of radio buttons. Examples
h:selectBooleanCheckbox Checkbox. Examples
h:selectManyCheckbox Set of checkboxes. Examples
h:selectManyListbox Multiselect listbox. Examples
h:selectManyMenu Multiselect menu. Examples
h:panelGrid HTML table
h:panelGroup Two or more components that are laid out as one
h:dataTable A feature-rich table control
h:column Column in a dataTable

Table 4–4 Basic Attributes

Attribute Component Types Description
id A (25) Identifier for a component
binding A (25) Reference to the component that can be used in a backing bean
rendered A (25) A boolean; false suppresses rendering
styleClass A (23) Cascading stylesheet (CSS) class name
value I, O, C (19) A component’s value, typically a value binding
valueChangeListener I (11) A method binding to a method that responds to value changes
converter I, O (15) Converter class name
validator I (11) Class name of a validator that’s created and attached to a component
required I (11) A boolean; if true, requires a value to be entered in the associated field

A = all, I = input, O = output, C = commands, (n) = number of tags with attribute

Table 4–5 HTML 4.0 Pass-through Attributes

Attribute Description
accesskey (14) A key, typically combined with a system-defined metakey, that gives focus to an element
accept (1) Comma-separated list of content types for a form
accept-charset (1) Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset.
alt (4) Alternative text for nontextual elements such as images or applets
border (4) Pixel value for an element’s border width
charset (3) Character encoding for a linked resource
coords (2) Coordinates for an element whose shape is a rectangle, circle, or polygon
dir (18) Direction for text. Valid values are ltr (left to right) and rtl (right to left).
disabled (11) Disabled state of an input element or button
hreflang (2) Base language of a resource specified with the hrefhreflang may only be used with href. attribute;
lang (20) Base language of an element’s attributes and text
maxlength (2) Maximum number of characters for text fields
readonly (11) Read-only state of an input field; text can be selected in a readonly field but not edited
rel (2) Relationship between the current document and a link specified with the href attribute
rev (2) Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types.
rows (1) Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute.
shape (2) Shape of a region. Valid values: default, rect, circle, poly. (default signifies the entire region)
size (4) Size of an input field
style (23) Inline style information
tabindex (14) Numerical value specifying a tab index
target (3) The name of a frame in which a document is opened
title (22) A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
type (4) Type of a link; for example, "stylesheet"
width (3) Width of an element

(n) = number of tags with attribute

Table 4–6 DHTML Event Attributes

Attribute Description
onblur (14) Element loses focus
onchange (11) Element’s value changes
onclick (17) Mouse button is clicked over the element
ondblclick (18) Mouse button is double-clicked over the element
onfocus (14) Element receives focus
onkeydown (18) Key is pressed
onkeypress (18) Key is pressed and subsequently released
onkeyup (18) Key is released
onmousedown (18) Mouse button is pressed over the element
onmousemove (18) Mouse moves over the element
onmouseout (18) Mouse leaves the element’s area
onmouseover (18) Mouse moves onto an element
onmouseup (18) Mouse button is released
onreset (1) Form is reset
onselect (11) Text is selected in an input field
onsubmit (1) Form is submitted

(n) = number of tags with attribute

Table 4–7 Attributes for h:form

Attribute Description
binding, id, rendered, styleClass Basic attributes
accept, acceptcharset, dir, enctype, lang, style, target, title HTML 4.0 attributes
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onreset, onsubmit DHTML events


Table 4–8 Attributes for h:inputText, h:inputSecret, h:inputTextarea,and h:inputHidden


Attribute Description
cols For h:inputTextarea only—number of columns
immediate Process validation early in the life cycle
redisplay For h:inputSecret only—when true, the input field’s value is redisplayed when the web page is reloaded
required Require input in the component when the form is submitted
rows For h:inputTextarea only—number of rows
valueChangeListener A specified listener that’s notified of value changes
binding, converter, id, rendered, required, styleClass, value, validator Basic attributes
accesskey, alt, dir, disabled, lang, maxlength, readonly, size, style, tabindex, title HTML 4.0 pass-through attributes—alt, maxlength, and size do not apply to h:inputTextarea. None apply to h:inputHidden.
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onselect DHTML events. None apply to h:inputHidden.

Table 4–9 h:inputText and h:inputSecret Examples

Example Result

.

.

.

.

.

.

Table 4–10 h:inputTextarea Examples

Example Result

.

.

.

.

Table 4–11 Attributes for h:outputText and h:outputFormat

Attribute Description
escape If set to true, escapes <, >, and & characters. Default value is true.
binding, converter, id, rendered, styleClass, value Basic attributes
style, title HTML 4.0

Attributes for h:outputLabel

Attribute Description
for The ID of the component to be labeled.
binding, converter, id, rendered, value Basic attributes

Table 4–12 Attributes for h:graphicImage

Attribute Description
binding, id, rendered, styleClass, value Basic attributes
alt, dir, height, ismap, lang, longdesc, style, title, url, usemap, width HTML 4.0
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Table 4–13 h:outputText and h:graphicImage Examples

Example Result

.

.
"/> .
"/> .

.

.

Table 4–14 h:commandButton and h:commandLink

Attribute Description
action If specified as a string: Directly specifies an outcome used by the navigation handler to determine the JSF page to load next as a result of activating the button or link If specified as a method binding: The method has this signature: String methodName(); the string represents the outcome
actionListener A method binding that refers to a method with this signature: void methodName(ActionEvent)
charset For h:commandLink only—The character encoding of the linked reference
image For h:commandButton only—A context-relative path to an image displayed in a button. If you specify this attribute, the HTML input’s type will be image.
immediate A boolean. If false (the default), actions and action listeners are invoked at the end of the request life cycle; if true, actions and action listeners are invoked at the beginning of the life cycle. See Chapter 6 for more information about the immediate attribute.
type For h:commandButton: The type of the generated input element: button, submit, or reset. The default, unless you specify the image attribute, is submit. For h:commandLink: The content type of the linked resource; for example, text/html, image/gif, or audio/basic
value The label displayed by the button or link. You can specify a string or a value reference expression.
accesskey, alt, binding, id, lang, rendered, styleClass, value Basic attributes
coordsh:commandLinkdir, disabledh:commandButtonhreflangh:commandLinklang, readonly, relh:commandLinkrevh:commandLinkshapeh:commandLinkstyle, tabindex, targeth:commandLinktitle, type ( only), ( only), ( only), ( only), ( only), ( only), ( only), HTML 4.0
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect DHTML events

Table 4–15 h:commandButton Examples

Example

Result

.

.

.

.

.

Table 4–16 h:commandLink Examples

Example Result

.

.

.


.

.

Table 4–17 Attributes for h:outputLink

Attribute Description
accesskey, binding, converter, id, lang, rendered, styleClass, value Basic attributes
charset, coords, dir, hreflang, lang, rel, rev, shape, style, tabindex, target, title, type HTML 4.0
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Table 4–18 h:outputLink Examples

Example Result

.

.

.

.

Table of Contents

.

Table 4–19 Selection Tag Examples

Tag Generated HTML Examples
h:selectBooleanCheckbox .
h:selectManyCheckbox ... ...
.
h:selectOneRadio ... ...
.
h:selectOneListbox .
h:selectManyListbox .
h:selectOneMenu .
h:selectManyMenu .

Table 4–20 Attributes for h:selectBooleanCheckbox, h:selectManyCheckbox, h:selectOneRadio, h:selectOneListbox, h:selectManyListbox, h:selectOneMenu, h:selectManyMenu

Attribute Description
disabledClass CSS class for disabled elements—for h:selectOneRadio and h:selectManyCheckbox only
enabledClass CSS class for enabled elements—for h:selectOneRadio and h:selectManyCheckbox only
layout Specification for how elements are laid out: lineDirection (horizontal) or pageDirectionh:selectOneRadio and h:selectManyCheckbox only (vertical)—for
binding, converter, id, immediate, styleClass, required, rendered, validator, value, valueChangeListener Basic attributes
accesskey, border, dir, disabled, lang, readonly, style, size, tabindex, title HTML 4.0—border is applicable to h:selectOneRadioh:selectManyCheckbox only. size is applicable to h:selectOneListbox and h:selectManyListbox only. and
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect DHTML events

Table 4–21 Attributes for f:selectItem

Attribute Description
binding, id Basic attributes
itemDescription Description used by tools only
itemDisabled Boolean value that sets the item’s disabled property
itemLabel Text shown by the item
itemValue Item’s value, which is passed to the server as a request parameter
value Value binding expression that points to a SelectItem instance

Attributes for f:selectItems

Attribute Description
binding, id Basic attributes
value Value binding expression that points to a SelectItem, an array or Collection of SelectItem objects, or a Map mapping labels to values.

Table 4–22 Attributes for h:message and h:messages

Attribute Description
for The ID of the component whose message is displayed—applicable only to h:message
errorClass CSS class applied to error messages
errorStyle CSS style applied to error messages
fatalClass CSS class applied to fatal messages
fatalStyle CSS style applied to fatal messages
globalOnly Instruction to display only global messages—applicable only to h:messages. Default: false
infoClass CSS class applied to information messages
infoStyle CSS style applied to information messages
layout Specification for message layout: table or list—applicable only to h:messages
showDetail A boolean that determines whether message details are shown. Defaults are false for h:messages, true for h:message.
showSummary A boolean that determines whether message summaries are shown. Defaults are true for h:messages, false for h:message.
tooltip A boolean that determines whether message details are rendered in a tooltip; the tooltip is only rendered if showDetail and showSummary are true
warnClass CSS class for warning messages
warnStyle CSS style for warning messages
binding, id, rendered, styleClass Basic attributes
style, title HTML 4.0

Table 4–23 Attributes for h:panelGrid

Attribute Description
bgcolor Background color for the table
border Width of the table’s border
cellpadding Padding around table cells
cellspacing Spacing between table cells
columnClasses Comma-separated list of CSS classes for columns
columns Number of columns in the table
footerClass CSS class for the table footer
frame frame Specification for sides of the frame surrounding the table that are to be drawn; valid values: none, above, below, hsides, vsides, lhs, rhs, box, border
headerClass CSS class for the table header
rowClasses Comma-separated list of CSS classes for columns
rules Specification for lines drawn between cells; valid values: groups, rows, columns, all
summary Summary of the table’s purpose and structure used for non-visual feedback such as speech
binding, id, rendered, styleClass, value Basic attributes
dir, lang, style, title, width HTML 4.0
onclick, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Table 4–24 Attributes for h:panelGroup

Attribute Description
binding, id, rendered, styleClass Basic attributes
style HTML 4.0

Table 5–1 Attributes for h:dataTable

Attribute Description
bgcolor Background color for the table
border width of the table's border
cellpadding Padding around table cells
cellspacing Spacing between table cells
columnClasses comma-separated list of CSS classes for columns
first index of the first row shown in the table
footerClass CSS class for the table footer
frame Specification for sides of the frame surrounding the table should be drawn; valid values: none, above, below, hsides, vsides, lhs, rhs, box, border
headerClass CSS class for the table header
rowClasses comma-separated list of CSS classes for rows
rules Specification for lines drawn between cells; valid values: groups, rows, columns, all
summary summary of the table's purpose and structure used for non-visual feedback such as speech
var The name of the variable created by the data table that represents the current item in the value
binding, id, rendered, styleClass, value Basic attributes
dir, lang, style, title, width HTML 4.0
onclick, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Attributes for h:column

Attribute Description
headerClass (JSF 1.2) CSS class for the column's header
footerClass (JSF 1.2) CSS class for the column's footer
binding, id, rendered Basic attributes

Table 6–1 Attributes for f:convertNumber

Attribute Type Value
type String number (default), currency , or percent
pattern String Formatting pattern, as defined in java.text.DecimalFormat
maxFractionDigits int Maximum number of digits in the fractional part
minFractionDigits int Minimum number of digits in the fractional part
maxIntegerDigits int Maximum number of digits in the integer part
minIntegerDigits int Minimum number of digits in the integer part
integerOnly boolean True if only the integer part is parsed (default: false)
groupingUsed boolean True if grouping separators are used (default: true)
locale java.util.Locale Locale whose preferences are to be used for parsing and formatting
currencyCode String ISO 4217 currency code to use when converting currency values
currencySymbol String Currency symbol to use when converting currency values

Table 6–2 Attributes for f:convertDateTime

Attribute Type Value
type String date (default), time, or both
dateStyle String default, short, medium, long, or full
timeStyle String default, short, medium, long, or full
pattern String Formatting pattern, as defined in java.text.SimpleDateFormat
locale java.util.Locale Locale whose preferences are to be used for parsing and formatting
timeZone java.util.TimeZone Time zone to use for parsing and formatting

Table 6–3 Standard Validators

JSP Tag Validator Class Attributes Validates
f:validateDoubleRange DoubleRangeValidator minimum, maximum a double value within an optional range
f:validateLongRange LongRangeValidator minimum, maximum a long value within an optional range
f:validateLength LengthValidator minimum, maximum a String with a minimum and maximum number of characters

Attributes for f:view

Attribute Description
locale The locale for this view.
renderKitId (JSF 1.2) The render kit ID for this view
beforePhase, afterPhase Phase listeners that are called in every phase except "restore view"

Attributes for f:subview

Attribute Description
binding, id, rendered Basic attributes

Attributes for f:facet

Attribute Description
name The name of this facet.

Attributes for f:attribute

Attribute Description
name The name of the attribute to set.
value The value of the attribute.

Attributes for f:param

Attribute Description
name An optional name for this parameter component.
value The value stored in this component.
binding, id Basic attributes

Attributes for f:actionListener, f:valueChangeListener

Attribute Description
type The name of the listener class

Attributes for f:propertyChangeListener

Attribute Description
target The bean property to set when the action event occurs
value The value to set it to

Attributes for f:converter

Attribute Description
converterId The ID of the converter

Attributes for f:validator

Attribute Description
validatorId The ID of the validator

Attributes for f:loadBundle

Attribute Description
basename The resource bundle name
value The name of the variable that is bound to the bundle map

Attributes for f:verbatim

Attribute Description
escape If set to true, escapes <, >, and & characters. Default value is false.
rendered (JSF 1.2) Basic attributes

Click here to View more...