29. Using Javascript

PROBLEM

Most web applications make some use of javascript. Whether doing AJAX-based development, client-side validation, or some other capability powered by javascript, a web application will more than likely need to include some third-party and custom javascript libraries.

SOLUTION

Javascript is added to Spring-based applications generated by Skyway Builder in the same manner as they are added to any web application.

HOW IT WORKS

The javascript can be added inline, in which case it will be contained in the JSP files wrapped by the <script> tag.

Example 2.33. Inline javascript

<script type="text/javascript">
<!--
function helloWorld() {
    alert('Hello World!') ;
}
// -->
</script>
      

Third-party or custom Javascript libraries can be added to the web project, and they will be automatically included in the packaged/deployed application. It's up to the UI developer to reference (include) the javascript libraries in the JSP page.

The steps for using a javascript library from within a JSP is:

  1. Copy the files into the web project. The files can organized using whatever folder structure is desire.

  2. Reference the files within the user interface by URL.

One of the web project folders that is automatically created with a new project is the "js" folder. This folder is used to store the javascript files used by Skyway's web controls. In the folder there are three javascript files. The prototype.js file is used to support Skyway's AJAX functionality, and the other two libraries are light-weight javascript libraries from Skyway for bridging the prototype library with Skyway's web controls. If you have some additional 3rd party or custom javascript libraries that you want to include in the web application, you can add them to the js folder (or any folder for that matter) and load them from your web application.

For example if you add the script.aculo.us javascript library (scriptaculous.js) to the js folder in the web project, the javascript library can be loaded into a JSP page using one of the following references:

Example 2.34. Linking to javascript libraries

<script src="${pageContext.request.contextPath}/js/scriptaculous.js" type="text/javascript"/>
</script>

-or-

<skyway:javascript src="scriptaculous.js"></skyway:javascript>          

The first example uses the standard html <script> tag, and the src is specified using the ${pageContext.request.contextPath} variable along with the a reference to the "js" folder and the filename. The second example uses the <skyway:javascript> JSP tag. The advantage of the JSP tag is that you only need to specify the name of the javascript file. The tag will automatically derive the URL from the context root (so there's no need to specify the ${pageContext.request.contextPath} variable), and it will automatically look in the js folder.

RELATED RECIPES

  1. Using Absolute Paths for Images, CSS and Javascript

  2. Publishing a AJAX service using DWR