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 »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.