Question

I wanted to use absolute path in src attribute, while including Javascript and CSS files in JSP.

Using relative URLs would not serve my purpose, similar to the one below :

<script type="text/javascript" src="../js/jquery-1.6.4.min.js"></script>

If I use absolute URL like,

<script type="text/javascript" src="/appName/js/jquery-1.6.4.min.js"></script>

Then I am hard-coding web application name which is not suitable again...

The best option I found is :

<base href="${pageContext.request.contextPath}"  />

But, it only works on href attributes like <a href="home.jsp" />

Was it helpful?

Solution

You got your solution:

<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<a href="${pageContext.request.contextPath}/home.jsp">Home</a>

or, using the JSTL:

<script src="<c:url value="/js/jquery.js"/>"></script>
<a href="<c:url value="/home.jsp"/>">Home</a>

The JSTL tag has the added advantage that it also adds the session ID to the URL if cookies are disabled, in order to track session using URL-rewriting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top