Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the contextPath from JavaScript, the right way?

Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why? I can think of a few possibilities. Am I missing any?

1. Burn a SCRIPT tag into the page that sets it in some JavaScript variable

<script>var ctx = "<%=request.getContextPath()%>"</script> 

This is accurate, but requires script execution when loading the page.

2. Set the contextPath in some hidden DOM element

<span id="ctx" style="display:none;"><%=request.getContextPath()%></span> 

This is accurate, and doesn't require any script execution when loading the page. But you do need a DOM query when need to access the contextPath. The result of the DOM query can be cached if you care that much about performance.

3. Try to figure it out within JavaScript by examining document.URL or the BASE tag

function() {     var base = document.getElementsByTagName('base')[0];     if (base && base.href && (base.href.length > 0)) {         base = base.href;     } else {         base = document.URL;     }     return base.substr(0,         base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1)); }; 

This doesn't require any script execution when loading the page, and you can also cache the result if necessary. But this only works if you know your context path is a single directory -- as opposed to the root directory (/) or the multiple directories down (/mypath/iscomplicated/).

Which way I'm leaning

I'm favoring the hidden DOM element, because it doesn't require JavaScript code execution at the load of the page. Only when I need the contextPath, will I need to execute anything (in this case, run a DOM query).

like image 553
Mike M. Lin Avatar asked Jul 07 '11 18:07

Mike M. Lin


People also ask

How do I get the context path in react?

In reactjs, when you are building your app for production, you need to run "npm run build". To build it correctly, you need to set the homepage property in package. json to the main url of your site. In my case I am using http://localhost:3000 for local development, and http://localhost:8080/myapp for stage testing.

What is ${ pageContext request contextPath?

${pageContext. request. contextPath} is an EL expression equivalent to the JSP expression <%= request. getContextPath() %> . It is recommended to use ${pageContext.


1 Answers

Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:

<script>var ctx = "${pageContext.request.contextPath}"</script> 
like image 109
Mike M. Lin Avatar answered Oct 03 '22 20:10

Mike M. Lin