Skip to content Skip to sidebar Skip to footer

How To Set Contextpath For An Image Link

i am trying to put context path for an image in HTML. Here /MyWeb is the ContextPath which is hardcoded. How can i get dynamically. i a

Solution 1:

First of all, "Context path" is a term which is typically used in JSP/Servlet web applications, but you didn't mention anything about it. Your question history however confirms that you're using JSP/Servlet. In the future, you should be telling and tagging what server side language you're using, because "plain HTML" doesn't have a concept of "variables" and "dynamic generation" at all. It are server side languages like JSP which have the capability of maintaining and accessing variables and dyamically generating HTML. JavaScript can be used, but it has its limitations as it runs in webbrowser, not in webserver.

The question as you initially have will only confuse answerers and yield completly unexpected answers. With question tags you reach a specific target group. If you use alone the [html] tag, you will get answers which assume that you're using pure/plain HTML without any server side language.


Back to your question: you can use ${pageContext.request.contextPath} for this.

<imgsrc="${pageContext.request.contextPath}/images/pageSetup.gif">

See also:

Solution 2:

You can't write JavaScript in the src attribute. To do what you want, try some code like this:

var img = newImage();
img.src = contextPath + "/images/pageSetup.gif";
document.getElementById('display').appendChild(img);

Here the target; the place where you want to display the image, is a div or span, with the id display.

Demo

With HTML, you'll have to take some extra traffic of producing an error, so you can replace the image, or you can send some traffic Google's way. Please do not use this:

<imgsrc='notAnImage'onerror='this.src= contextPath + "/images/pageSetup.gif" '>

Demo

Do not use this.

Solution 3:

You must use JavaScript for this.

First, have all images point to some dummy empty image on your domain while putting the real path as custom attribute:

<imgsrc="empty.gif"real_src="/images/pageSetup.gif" />

Now have such JavaScript code in place to iterate over all the images and change their source to use the context path:

var contextPath = "/MyRealWeb";
window.onload = function() {
    var images = document.getElementByTagName("img");
    for (var i = 0; i < images.length; i++) {
        var image = images[i];
        var realSource = image.getAttribute("real_src") || "";
        if (realSource.length > 0)
            image.src = contextPath + realSource;
    }
};

Post a Comment for "How To Set Contextpath For An Image Link"