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

JavascriptJspServlets

Javascript Problem Overview


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).

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

Got it :D

function getContextPath() {
   return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());

Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.

Solution 3 - Javascript

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

Solution 4 - Javascript

Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example: Http://localhost:8080/bla/bla

Javascript:

var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)); 
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";

Solution 5 - Javascript

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

Solution 6 - Javascript

A Spring Boot with Thymeleaf solution could look like:

Lets say my context-path is /app/

In Thymeleaf you can get it via:

<script th:inline="javascript">
    /*<![CDATA[*/
		let contextPath    = /*[[@{/}]]*/
	/*]]>*/
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike M. LinView Question on Stackoverflow
Solution 1 - JavascriptMike M. LinView Answer on Stackoverflow
Solution 2 - JavascriptCedric SimonView Answer on Stackoverflow
Solution 3 - Javascriptuser159088View Answer on Stackoverflow
Solution 4 - JavascriptArmando CordovaView Answer on Stackoverflow
Solution 5 - JavascriptOleg ShavrovView Answer on Stackoverflow
Solution 6 - JavascriptMichael HegnerView Answer on Stackoverflow