Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

javascript include issue

 
Luke Shannon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to include a javascript file:

<script type="text/javascript" src="../htmlarea.js"></script>

I have this line in the head of my jsp. It doesn't work. It seems the page is loading its content not from where I think it is (I though it would load it from the same directory the jsp is stored in).

What is the correct way to do this?

Thanks,

Luke
[ May 24, 2005: Message edited by: Luke Shannon ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65111
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't rely on URL-relative references in a web app. Make your JS file reference relative to the app context.

For example, if your app context is named "/xyz" and your JS files are in a folder at the context root named scripts:



This will work regardless of which page the tag is in, or what the current URL is.

Of course that brings us to the fact that hard-coding the context path as above is a Bad Thing™. So what do you do?

You can obtain the context path under JSP 2.0 with:



or under JSP 1.x with:



So, your scipt tags would look like one of the following:



Depending upon your JSP version.

Or

You could use the context path mechanisms shown above to set the base of relative references using the <base> tag.

Or

You could write a custom tag that takes care of all of this for you.

[ May 24, 2005: Message edited by: Bear Bibeault ]
[ May 24, 2005: Message edited by: Bear Bibeault ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65111
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. This isn't just a JS file include issue. You also run into the same issues with image references and stylesheet references.

P.P.S. I usually use the custom tag route -- not just to get around this issue, but to provide "skinning" of my apps by making the image, stylesheet and script references adjust for whatever the current "skin" is.
 
Luke Shannon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. All set now.

I went with the following for now:



I haven't played with custom tags yet. I really don't know what they even do. I plan on reading HF Sevlets and JSP to figure them out the minute this project gets under control.

Luke
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic