Wednesday, December 13, 2006

More JSP Hacking in JSF

Previously I put some notes on using JSP EL in JSF pages. The useful thing for me was that you could embed EL in JavaScript such as Google Map API calls. But this only goes so far. For example, suppose you want to iterate over a String array that is defined in your backing bean. You can't do the following, unfortunately:

<script>
for(i=0; i < ${mybean.myStrings.length} ; i++ ) { document.write(${mybean.myStrings[i]}) } </script> ${mybean.myStrings.length} will work (if I recall correctly). The problem is that the EL expression inside the loop must be evaluated on the server side when the JSP/JSF page is created, but the JavaScript is processed by the browser. If you really needed to do something like the above, you have to drive the loop with Java inside your JSF page. First, of course, you should realize your JSF backing session beans will be available in the usual way through the built-in JSP session object. <% MyBean mybean=(MyBean)session.getAttribute("mybean");
for(int i=0;i < mybean.myStrings.length;i++){
%>

<script>
document.write(<% myBean.myString[i] %>);
</script>

<%
}
%>

This example is really artificial, of course, but there really are cases when I needed to do things like this. OK, probably there is a better way.

No comments: