Server script inside js (javascript) files

I develop web application behind portal architecture. I needed to use some tag libraries provided by the portal, in my case plumtree, inside some functions that are implemented in a .js file.

Inside this type of files, the taglibraries and other kind of server side scripting, wont be interpretated ’cause server will treat these files as simple text files.

The main solution was always the one to include those javascript functions directly inside the jsp file. But I don’t like it.

Search search and search, try try and try, J2EE technology comes in our help.

It’s enough to create a jsp file where inside you’ll define all the needed javascript functions. Actually my file looks like the following

<pt:namespace pt:token="$$TOKEN$$" xmlns:pt='http://www.plumtree.com/xmlschemas/ptui/'/>
function farewell$$TOKEN$$(){
alert("farewell world");
return;
}

The first line is a taglibrary declaration that make every occurency of $$TOKEN$$ to be replaced by the unique indetifier (id) of the running portlet.

The habits to assign the portlet id to the function is given by the needing of avoid function naming collision inside portal pages where there are more than application sharing the same space as they were only a single web page.

Now you need to tell in some way that this jsp file must be seen by the application as a simple js one. Well, let’s go the web.xml file and add a servlet mapping for the just created jsp.

<servlet>
<servlet-name>try</servlet-name>
<display-name>try</display-name>
<jsp-file>/try.jsp</jsp-file>
</servlet>

and tell that it must be seen as javascript file

<servlet-mapping>
<servlet-name>try</servlet-name>
<url-pattern>/js/try.js</url-pattern>
</servlet-mapping>

Then inside the jsp calling the function use the usual javascript to include the js file

<pt:namespace pt:token="$$TOKEN$$" xmlns:pt='http://www.plumtree.com/xmlschemas/ptui/'/>
<script language="javascript" src="js/prova.js"></script>
<a href="javascript: farewell$$TOKEN$$();">click</a>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s