当我输入以下内容时,Eclipse 给了我各种邪恶的魔力:
<img src=<%if(request.getParameter("x")==null){"/images/x.gif">}
else{"get-it?x=<%=request.getParameter("x")}%>">
如果动态生成的图像的参数为空,则指定要显示的默认图像的正确语法是什么?另外,我可能想添加其他条件来显示默认图像。
我应该补充一点,这是一个由 java servlet 控制的 jsp 页面。
最佳答案
使用EL
(Scriplet 很久以前就死了):
<c:set var="imgURL" value="get-it?x=${param.x}" />
<img src="${empty param.x ? '/images/x.gif' : imgURL}" />
或者您也可以在不设置其他属性的情况下执行此操作:
<img src="${empty param.x ? '/images/x.gif' : 'get-it?x='}${param.x}" />
如果您只有 if-else
,三元运算符就可以工作。 。正如@Sotirios 的评论中所述,如果您有多个条件可供选择 - if-else if-else
梯子,那么你需要使用<c:choose>
标签。
注意,您需要在 lib
中添加 JSTL 库文件夹,并包含核心标签库。
话虽如此,您还应该考虑在 Servlet 本身中准备 Image URI,转发到 JSP。
假设您有一个 HTML 表单:
<form action="/servlet1" method="POST">
<input type = "text" name="x" />
</form>
在映射于 /servlet1
的 Servlet 中,你应该得到参数 x
,并据此创建图像 URL。然后将该图像 URL 放入请求属性中:
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
然后在JSP页面中,您可以获取*imageURL*
,使用EL
:
<img src="${imageURL}" />
看,我只需要一个 Servlet。看一下,如果我漏掉了什么,请评论。我认为您想要做的事情只需使用一个 Servlet 即可完成。
另请参阅:
关于java - 使用java控制在html img标签中渲染哪个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084529/