'Import an image to jsp file using <c:import url=""/>
How can I automatically get the file path of an image using <c:import url=""/> as src of <img src="" alt""/>
To be more specific, below is the requiment:
Create a card with the following structure
<c:ImportUrl url = “…”/>
here url property will work like this:
url = “/img/avatar.png” the url attribute can point to the address of
any resource.
if current context (current path is /list)
then automatically c:ImportUrl will return the text containing the command to convert from
current context to the resource pointed to by the url.
Eg:
We have the context: build the page /list according to the MVC pattern
when every request goes through Controller, instead of direct request
to the view (usually written in jsp).
Whether the jsp file address is : /view/test/list.jsp
The address of an image file to include in the view is: /img/avatar.png
To show this image file
<img src = “<c:ImportUrl url="/img/avatar.png”/>”
Solution 1:[1]
You can assign the value of the generated url into a variable and then use that variable:
<c:import var="image" url="/img/avatar.png"/>
<img src = "${image}" alt="..." />
Solution 2:[2]
Using a Data URL and Base 64 encoding works, but you might have to force a specific character encoding/content-type character set.
Here is a JSP excerpt that uses JSP scriptlet to do the Base64 encoding:
<c:import url="https://my.server.com/get-png-data" var="imageData"/>
<% String base64data = java.util.Base64.getEncoder().encodeToString( ((String) pageContext.getAttribute("imageData")).getBytes()); %>
<img src="data:image/png;base64,<%=base64Data%>"/>
On a couple of systems, I had to explicitly use ...getBytes("ISO-8859-1").
I'd also recommend, by the way, wrapping that <c:import> in a <c:catch> in case there are failures. Like this:
<c:catch var="importException">
<c:import url="https://my.server.com/get-png-data" var="imageData"/>
...
</c:catch>
<c:if test="${not empty importException}">
<c:out value="${importException}"/> <%-- do something else here to handle --%>
</c:if>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luiggi Mendoza |
| Solution 2 |
