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=''/>
function farewell$$TOKEN$$(){
alert("farewell world");

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.


and tell that it must be seen as javascript file


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

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


Leave a Reply

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

You are commenting using your 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