Use EL
(Scriplets are dead long back):
<c:set var="imgURL" value="get-it?x=${param.x}" />
<img src="${empty param.x ? '/images/x.gif' : imgURL}" />
or you can also do it without setting another attribute:
<img src="${empty param.x ? '/images/x.gif' : 'get-it?x='}${param.x}" />
Ternary operator will work if you just have an if-else
. As stated in comments by @Sotirios if you have multiple conditions to choose from - if-else if-else
ladder, then you would need to use <c:choose>
tag.
Note, you need to add JSTL libraries in your lib
folder, and include the core taglib.
Having said all that, you should also consider preparing the Image URI in the Servlet itself, forwarding to a JSP.
Suppose you have an HTML form:
<form action="/servlet1" method="POST">
<input type = "text" name="x" />
</form>
In Servlet mapped at /servlet1
, you should get the parameter x
, and create the Image URL based on that. And then put that image url in request attribute:
String x = request.getParameter("x");
if (x == null) {
// Set Default image in request attribute
request.setAttribute("imageURL", "images/x.gif");
} else {
// Else create the image, and set it in request attribute
resp.setContentType("image/gif");
BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
GetBI fetchBI = new GetBI();
bi = fetchBI.get_bi(x);
ImageIO.write(bi,"gif",resp.getOutputStream());
request.setAttribute("imageURL", "get-it?x="+x);
}
// Forward the request to the required JSP
then in JSP Page, you can fetch the *imageURL*
, using EL
:
<img src="${imageURL}" />
See, I just needed one Servlet. Take a look, and comment, if I missed something. I think what you want to do can be done simply using a single Servlet.
See also: