Dynamic HTML Base Tag Generation in JSP: A Clean Solution

This technical guide demonstrates how to programmatically set the HTML base tag in JSP pages using JSTL and JSP's page context. The solution involves computing the correct URL by manipulating the request URL and URI, ensuring proper resolution of relative paths for static resources. This approach is particularly useful for maintaining consistent path references across different deployment contexts and server configurations.

1 Minutes reading time

Behold the masterpiece that AI hallucinated while reading this post:

"The Little JSP That Could: A Tale of Finding Its Base"

(after I fed it way too many marketing blogs and memes)

Created using DALL-E 3

AI-Generated: The Little JSP That Could: A Tale of Finding Its Base

Sometimes we have to set the HTML base Tag from within a JSP page. For this purpose, we have to compute the correct URL, because the JSP API does not fully expose it. The following shipped shows how it can be cone:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
<!doctype html>
<html>
    <head>
        <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
    </body>
</html>

Git revision: 2e692ad