23 March 2011

How to add js file to jsp file and how to solve problems related to adding javascript file to jsp file

So you using creating jsp file and you want add js file and you think it simple because jsp is like html so ....

Peace of cake.
And you add this line:
<script language="JavaScript" type="text/javascript" src="./js/amazingscript.js"></script>

and Firebug and see 404 file not found

and you thinking what a minute... but file is there! What are you talking about ?
So you looking for solution on Internet and you see that you have 2 solutions:

1) You should put
in head (or between </head> and <body> it is wrong place to put it but it will work usually)
<script language="JavaScript" type="text/javascript" src="./js/amazingscript.js"></script>

2)You should put
<jsp:include page="./js/amazingscript.js"></jsp:include>

In many cases both solution doesn't work or weird things happen.
Why ?

In case 1) you will see error that file is not found
because: either this file really DOESN'T EXIST (because of misspell , remember about case sensitive !) or you put file in area which in place which is not accessible (like inside WEB-INF folder ).

In case 2) you will see your source code as plain text in browser instead of result of execution javascript
because jsp is executed on SERVER SIDE (server) and js is executed on CLIENT SIDE (user's browser)!

What else can go wrong?
It usually problem with path  (more about path i will  write in next post )

How to include JavaScript file in jsp file that will be work?

1)First put JavaScript in place where can be accessed!(For example :everything stored in WEB-INF folder will not work!!if you using spring framework).

2)Use script tag <script language="JavaScript" type="text/javascript" src="./js/amazingscript.js"></script>

ps. be careful as well with path (more about path