Blog Archives

November 15th, 2010
11:56 am
Namespace error when using JSTL in Facelets with JSF 2.0

Posted under JSF
Tags , , , , ,

Update 6/7/2011

I hit this problem again when accidentally ignoring the Eclipse warning.
This time, the problem prevented <c:if> tags from working correctly – the tags always tested as true. This was especially nasty as the cause did not appear related to the problem I was having. See this issue in Mantis about the problem.

Original Post

I was using the following namespace declaration in order to use JSTL (c:if etc.) on a Facelets/JSF 2.0 page, as I had done successfully previously under JSF 1.2:-

xmlns:c=”http://java.sun.com/jstl/core

This gave rise to the following warning in Eclipse:-

NLS missing message: CANNOT_FIND_FACELET_TAGLIB in: org.eclipse.jst.jsf.core.validation.internal.facelet.messages

The namespace is incorrect, and as pointed out here (in Ryan Lubke’s comment on the post) should now be:-

xmlns:c=”http://java.sun.com/jsp/jstl/core

This fixed the problem. A complete listing of the namespaces for the tag libraries is also available in edition 3 of Core JavaServer Faces, at the start of Chapter 4, page 101 – (edition 2 did not have this table; it is a useful addition).

No Comments »

November 8th, 2010
12:26 pm
Using JSTL Functions in JSF EL e.g. to return list size

Posted under JSF
Tags , , ,

Unfortunately some methods of backing beans, such as size() to return the number of entries in a list in a bean, are not directly callable from an EL expression as they are not exposed as standard getters. Whilst expressions on a facelets page should be used with care so as not to include business logic on the page, they are sometimes useful. One of my use cases has been to optionally add a css class into a stylclass attribute to correct the width of a table header when scrollbars are present (when enough rows are present to cause scrolling).

You can add additional properties to the beans to do this, but an easier way is often to use JSTL functions on the page. The following declaration includes the namespace for them, using prefix fn:-

<!DOCTYPE HTML>
<html xmlns=”http://www.w3c.org/1999/xhtml”
xmlns:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:fn=”http://java.sun.com/jsp/jstl/functions”
xmlns:p=”http://primefaces.prime.com.tr/ui”>

 

The following code fragment calls the length function to return the size of a list :-

<p:dataTable var=”car” value=”#{tableBean.carsSmall}” scrollable=”true” 
         styleClass=”#{fn:length(tableBean.carsSmall) lt 8 ? ” : ‘ss-tableheader-scrolladjust’}” height=”200″ >

 The javadoc for the complete set of jstl functions may be found here.

No Comments »

November 4th, 2010
1:54 pm
How to add inline Javascript to a Facelets/XHTML page

Posted under JSF
Tags , , , ,

This is not immediately obvious; the following are the key points:-

  • The Javascript code between the script tags needs to be embedded in XML “CDATA” sections
  • The CDATA open and close tags need to be preceded with Javascript comment markers “//”
  • You can freely use JSF Expression language within the Javascript and it will be evaluated and inserted (as with the “request.contextPath” below)

The following example xhtml page illustrates this:-

<!DOCTYPE HTML>
<html xmlns=’http://www.w3c.org/1999/xhtml’
   xmlns:f=’http://java.sun.com/jsf/core’
   xmlns:h=’http://java.sun.com/jsf/html’>
<f:view contentType=”text/html”>
<h:head>
<script type=”text/javascript”>
//<![CDATA[
    alert(“Hello World from #{request.contextPath}”);
//]]>
</script>
</h:head>
<h:body></h:body>
</f:view>
</html>

No Comments »

September 26th, 2010
11:28 am
Choosing a DOCTYPE for maximum browser compatibility and standards mode

Posted under HTML
Tags , , , , , , ,

This follows on from my previous post which highlighted an example of a valid DOCTYPE which still threw IE into Quirks mode.

The DOCTYPE issue has been something of a minefield – there are a number of different declarations and they are relatively complex, some have browser compatibility issues, and then of course different ones are needed for XHTML/facelets use.

It seems the holy grail of simplifying all of this is just to stick to the remarkably simple and highly compatible HTML5 DOCTYPE:-

<!DOCTYPE html>

  • This has the following highly desirable characteristics:-
  • It triggers standards mode for all known modern browsers
  • It is backwards compatible
  • It works with HTML pages and facelets/XHTML

See these posts here, here and here for more discussion on this.

It really does seem to solve all the DOCTYPE pain – I think I’ve died and gone to heaven!

No Comments »

September 25th, 2010
11:32 am
Primefaces test application does not display correctly with Google Chrome

Posted under JSF
Tags , , , , ,

A simple Primefaces table sample application was not displaying in Chrome. Some of the output data from the cells plus some other metadata was displayed as raw text with no formatting.

This answer to FAQ question 6 in the documentation PDF details the problem and the solution:-

6. With facelets some components like charts do not work in Safari or Chrome but there?s no problem with Firefox.
The common reason is the response mimeType when using with PrimeFaces with facelets. You need to make sure responseType is “text/html”. With facelets you can use the <f:view contentType=”text/html”> to enforce this setting.

I added this to the sample code and Chrome then worked correctly. I checked the Primefaces Showcase and note that the same is done there.

No Comments »

January 8th, 2010
9:30 pm
JSF 1.2/Facelets event & state handling

Posted under JSF
Tags , , ,

The issue here came about when trying to propagate click events from a child table pair tag to its parent facelet page. The table pair contained buttons to move rows between the tables, and to reorder rows on the target table – a typical design pattern used in this case to assign roles and rights to a user. The table pair tag is responsible for all the buttons for this function – move row selection left/right, move all left/right, reorder target row selection up, reorder target row selection down.

My general design in this situation is for the backing bean structure to mirror the objects on the page. There is therefore an overall page bean which has a child table pair bean for the table pair facelet tag, which in turn has 2 child table beans for its subsidiary facelet table tags. Whilst the parent facelet page does not need to know about the above button logic (it just pulls the result rows out of the child beans e.g. when a save is done), it does need to know when the child table pair has caused the page to be dirty, i.e. to have unsaved changes, which comes about when one of the above buttons is clicked.

My ideal solution to this would be to add an additional action listener on the table pair buttons – the main one is handled by the table pair bean, and an additional one on each button calls a single method on the overall page bean to notify that the page has changed. The parent does not need to know which button was clicked or why, but merely to know that a change has occurred. However this idea is scuppered in JSF 1.2 by the fact that a secondary f:actionListener tag on a button does not accept a method binding like the primary actionListener, but takes a fully qualified class name which must implement the ActionListener interface. This is a right pain as it is a class and not even an instance – you cannot tie the event to a particular bean.

My next attempt was to simply inject a parent reference in the TablePair bean in faces-config.xml, however this fails because JSF does not allow cyclic references in faces-config.

My final solution was therefore to pass a value binding for my own ChangeListener interface on the parent bean to the TablePair tag as a parameter, and declare this on each button using f:attribute. The TablePair bean then fetches the bean reference from the attribute when its actionListener is fired and calls the notify method on the reference’s Change Listener implementation. (I could also have used setPropertyActionListener to simplify this but an ICEfaces bug prevented this working – setPropertyActionListener was being called after the actionListener so the latter only ever saw a null value). The following code fragment illustrates what was used to pull the reference out of the attribute (note that this is incomplete and imports etc. are missing) :-

// Calling code
  private static final String CHANGE_LISTENER_ATTRIBUTE = "changeListener";
  ...
  ChangeListener changeListener =
    JSFUtil.fetchComponentAttribute(actionEvent, CHANGE_LISTENER_ATTRIBUTE);
  if (changeListener != null)
    changeListener.notify(this);
...
// Utility Class
public class JSFUtil {
  public static<F> F fetchComponentAttribute(ActionEvent actionEvent, String attribute) {
    UIComponent component = actionEvent.getComponent();
    Map<String, Object> attributes = component.getAttributes();
    return (F)(attributes.get(attribute));
  }
}

When propagating changes like this, it is important that the design does not cause recursive notifications, for example where a change gets passed up from one child to a parent, back down from the parent to all its children, who send it back up and so on. To this end, I therefore distinguish between the following concepts to avoid this happening:-

  1. Action Notification Events are only propagated upwards from children to parents, and are only raised in respect of external actions,  for example when a button click in a child tag causes a change which the parent needs to know about. ActionNotifications are never raised as a result of a property change on a component which could have been initiated by a parent. For clarity, if an external action causes a property change and needs to propagate this upwards, it is the fact that an external action occurred which is being propagated, and not the fact that a property has changed, i.e. in JSF terms it is the result of an action event and not a value change event. This means that whilst such an external action will pass an event up as well as changing a property, if a parent directly changes the same property, no event will be propagated up.  A child cannot directly change properties in its parent so it needs this mechanism to tell the parent “something external such as a button or link click has happened in me which you need to be aware of”. Typically this will be because a click action on the child has made the whole page dirty and the parent therefore needs to change component state throughout the page to reflect this (for example to enable the save and discard buttons and disable navigation from the page). As notifications only travel upwards, recursive notifications cannot therefore occur.
  2. Property Changes are only performed by a component on itself or on its child components. On itself, it can change any of its internal properties. On a child component, it can change any of the publically changeable properties of the child. As stated above, such changes will never give rise to action notification event propagation. However, property changes can certainly propagate downwards as required.

The state determination of a JSF page or a custom component can become complex when a number of components need to be, for example, selectively enabled and disabled depending on various property combinations. If the logic to determine the state is scattered throughout the component’s managed bean, or even worse, is coded in value expressions on a JSF page, it is hard to make sense of the state determination logic, easy to miss logic that is required, and easy to break the state determination when the code is changed. Therefore, I always use a private changeState method on a bean to perform all the state determination and changes. Typically this will involve a ladder of if..else based logic which checks properties on the bean, and then for example sets or clears various enable/disable properties for the JSF components. In State Machine terms, the various properties of the bean are inputs to the changeState method, and the method uses these inputs to determine a new state for the bean, setting various properties for the new state. I am not fussy about the precise implementation of this – in complex cases, it may be worth using a state machine/state table driven approach to determine state, and maintain a ‘current state’ for the bean which is independant of the beans properties, but for most normal cases this is overkill. What is important is to use an implementation which is clear, correct and easy to maintain, and where the mechanism is easy to understand and flows naturally from the state change requirements. This method should be called whenever a change happens to any of the inputs which the method uses to determine state, and therefore will normally be called many times throughout the bean. If AOP is in use, this might be a good candidate for using a pointcut and advice to dynamically insert the calls, for example on various property changes. In typical cases, I end up with a dirty flag on the bean which indicates that something has changed, and the changeState method checks the flag and sets various enable/disable properties as required. It is therefore often worth having an overloaded version of changeState which allows new values of such inputs to be passed in and set, and then the state change logic performed, in a single call.

As mentioned earlier, I specifically do not perform any such logic on a JSF page. The presence of logic in value expressions on a JSF page is a warning bell as it may indicate that either MVC controller logic or worse,  business logic has been placed on the page. As an example, my TablePair bean allows the ‘move selected rows to destination’ button to be clicked if any rows have been selected in the source table – otherwise the button is disabled. It would be possible to code an ‘anyRowsSelected’ property on the bean, and call this property directly from the disable attribute on the JSF page. Whilst this is a simple example, I would contend that this effectively places a controller logic decision in the MVC view. The correct way would be for the disable property on the button to directly refer to an enable/disable flag on the bean, and for the changeState method in the bean to call anyRowsSelected as a method, and set the enable/disable flag as required. This removes all evidence of the logic from the view, and also means that if the logic changes, for example if other conditions can occur on the bean which affect the button state, the change is made in the correct place – only in the changeState method on the bean. The JSF page would not need to be touched and has no knowledge of this.

No Comments »

January 8th, 2010
3:25 pm
JSF: #{…} is not allowed in template text

Posted under JSF
Tags , , , , ,

This error can occur when loading a JSF/Facelets page :-

org.apache.jasper.JasperException: /home.jspx(16,17)
   #{...} is not allowed in template text

One reason for this, described on JavaRanch here, is that the JSF page is not being routed properly via the servlet mapping in web.xml. The following extract from web.xml shows a mapping for .iface, to route urls ending in .iface to the ICEfaces Persistent Faces Servlet:-

    <servlet-mapping>
        <servlet-name>Persistent Faces Servlet</servlet-name>
        <url-pattern>*.iface</url-pattern>
    </servlet-mapping>

Even though the page itself may be a .jspx file, using .jspx rather than .iface in the url would not route the page to the above servlet, causing it to be parsed incorrectly. This post describes the cause in more detail – the #{…} syntax is unified EL, which is not allowed in template text in a JSP (hence the error). In the above case the page was being treated as a JSP rather than a Facelet due to the incorrect routing.

No Comments »

January 8th, 2010
10:42 am
ICEfaces facelets strips DOCTYPE, puts IE in quirks mode

Posted under JSF
Tags , , , , ,

By default when you create a new ICEfaces Facelets project with a sample page, it codes the DOCTYPE directive directly. Unfortunately, this is stripped out during processing/rendering and does not  appear in the final HTML for the page. When running IE without a suitable DOCTYPE directive, it switches into Quirks Mode and is not fully standards compliant, which may cause pages to display incorrectly.

the DOCTYPE can be added back by using the <ice:outputDeclaration> tag. To do this, you also need to add an <f:view> tag as you would in JSP mode, as in the following example :-

<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns="http://www.w3.org/1999/xhtml"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:ice="http://www.icesoft.com/icefaces/component">
 <ice:outputDeclaration
  doctypeRoot="HTML" doctypePublic="-//W3C//DTD XHTML 1.0 Transitional//EN"
  doctypeSystem="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
 <html>
    <head>
    ...
    </head>
    <body>
    ...
    </body>
 </html>
</f:view>

The issue is discussed and solved in this ICEfaces forum post. Interestingly, a page created by ICEfaces for a  JSP (non-facelet) project also uses the <ice:outputDeclaration> tag, presumably for the same reason.

Note that you cannot omit the <f:view> tag and add the xmlns namespace declarations to the <ice:outputDeclaration> tag as this fails – the <f:view> tag needs to be present.

Another post about Quirks mode and DOCTYPE switching, which also contains a useful Bookmarklet (Javascript link) which will tell you directly what mode a page is running in, may be found here.

No Comments »

January 8th, 2010
10:22 am
Useful reference/tutorial sites on Facelets

Posted under JSF
Tags , , , ,

I have found the following sites useful :-

Tutorials

Reference Information

No Comments »

January 7th, 2010
7:33 pm
Some useful Sites / Tutorials about JSF & Facelets

Posted under JSF
Tags ,

Helpful simple post about how facelets actually works.
http://www.theserverside.com/discussions/thread.tss?thread_id=41855

JSF central Inside Facelets tutorial series :-
http://www.jsfcentral.com/facelets/

IBM Developerworks articles (can also be downloaded as PDFs from the sites)

Facelets :-
http://www.ibm.com/developerworks/java/library/j-facelets/

JSF for nonbelievers articles – good introduction to JSF:-
http://www.ibm.com/developerworks/java/library/j-jsf1
http://www.ibm.com/developerworks/java/library/j-jsf2/
http://www.ibm.com/developerworks/java/library/j-jsf3/
http://www.ibm.com/developerworks/java/library/j-jsf4/

No Comments »