1

I have a javascript file "util.js" which I am using in a jsp file. How to access the application context EL ${pageContext.request.contextPath} in the javascript file?

This EL is working if the javascript function is copied inside the JSP. But if I keep it in separate javascript file, this is not working.

bruno
  • 2,213
  • 1
  • 19
  • 31
srikanth
  • 11
  • 1
  • 1
  • 2

2 Answers2

3

Well, you can either have your .js file as a .jsp, but with Content-Type text/javascript (undesirable), or you can define javascript variables in your jsp that includes the .js file, and pass (or less desirable - use directly) those variables to the functions. For example:

<script type="text/javascript" src="js/scripts.js"></script>
<input type="button" 
     onclick="someExternalJavascriptFunction('${pageContext.request.foo}')" />
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Thanks for the reply. Yes it is one of the solution. I am wondering if the javascript file i am including in the JSP should also be translated while JSP page translation. This is happenign for javascript functions which are in the JSP file, but not for the JS file. – srikanth Nov 26 '10 at 06:45
  • the js file is not handled by the JSP servlet. Hence it will not have the el expressions evaluated. – Bozho Nov 26 '10 at 06:58
  • 1
    I have resolved this by changing the JS file to a JSP (util_js.jsp) file and including the JSP file with <%@ include file="util_js.jsp" %> – srikanth Nov 26 '10 at 08:21
  • 1. Set the content type of the JSP in that case. 2. If an answer has worked, on stackoverflow you are invited to mark it as accepted. – Bozho Nov 26 '10 at 08:22
2

I do not think you can use EL in javascript file itself. You might be able to use var application_context = ${pageContext.request.contextPath} in your jsp(probably a layout file), while the var application_context itself can be defined directly into the javascript file.

Jinesh Parekh
  • 2,131
  • 14
  • 18
  • Hi Jinesh Thanks for the answer. Can you elaborate little more with some example. – srikanth Nov 26 '10 at 06:41
  • Here is your test.js var application_context = "www.something.com" Your main.jsp would have – Jinesh Parekh Nov 26 '10 at 07:09
  • 1
    I resolved it by changing the JS file to JSP file. This may not be a better solution, but the way you suggested needs a lot of changes in my code. Thanks for your reply. – srikanth Nov 26 '10 at 08:24