static image (e.g. car.png)
<table><tr><td><img src="http://<somehost>:<someport>/images/car.png" /></td></tr></table>
(e.g. lookup by id=123456 and fetched via a servlet from the database)
<table><tr><td><img src="http://<somehost>:<someport>/doc?id=123456"/></td></tr></table>
We generate snippets of HTML code (as mentioned above) and store these in the database which is used to re-construct a user specific page in a dynamic fashion.
The problem in the above scenario is that somehost / someport is statically bound and stored in the database which I would like to avoid since If I have to upgrade to a different machine with a different IP all of the above calls will fail.
How to solve this in a generic fashion, so that I can bind at a later stage as for as host/port is concerned.
First of all, storing HTML in a database isn't a good idea. But ala.
As to the concrete problem, you could just define a HTML <base> tag which would make all relative URLs in the document become relative of it.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="r" value="${pageContext.request}" />
<base href="${fn:replace(r.requestURL, r.requestURI, '')}${r.contextPath}/" />
</head>
This way you can just use
<table><tr><td><img src="images/car.png" /></td></tr></table>
<table><tr><td><img src="doc?id=123456"/></td></tr></table>
Without the base you'll be dependent on the context path.
If you really want to parameterize them, then I would use java.text.MessageFormat. You can use {0}, {1}, {2}, etc as placeholders for the first, second, third, etc parameters.
<table><tr><td><img src="{0}/images/car.png" /></td></tr></table>
<table><tr><td><img src="{0}/doc?id=123456"/></td></tr></table>
You can grab the current host/port (and context!) from the HttpServletRequest as follows:
HttpServletRequest r = getItSomehow();
String base = r.getRequestURL().toString().replace(r.getRequestURI(), "") + r.getContextPath();
You can format the HTML from DB as follows:
String html = getItSomehow();
String formatted = MessageFormat.format(html, base);
And then display that in the JSP. You could even wrap this in a custom EL function. Even more, some MVC frameworks like JSF have also tags which uses MessageFormat under the covers. E.g.
<h:outputFormat value="#{bean.html}" escape="false">
<f:param value="#{bean.base}" />
</h:outputFormat>
Why don't you use this way? This should work
static image (e.g. car.png)
<table><tr><td><img src="images/car.png" /></td></tr></table>
(e.g. lookup by id=123456 and fetched via a servlet from the database)
<table><tr><td><img src="/doc?id=123456"/></td></tr></table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With