在 JSP 中包含/导入文件之前如何检查文件是否存在?
假设 requestScope.importMe 需要 JSP 文件的路径,
<c:choose>
<c:when test="${!empty requestScope.importMe && fileExists(requestScope.importMe) }">
<c:import url="${requestScope.importMe}" />
...
</c:choose>
如何在尝试包含该文件之前检查该文件是否存在,以免引发错误?
我更喜欢使用 JSTL 标签的解决方案。
Assuming that requestScope.importMe is expecting a path to a JSP file
<c:choose>
<c:when test="${!empty requestScope.importMe && fileExists(requestScope.importMe) }">
<c:import url="${requestScope.importMe}" />
...
</c:choose>
How can I check if the file exists before trying to include it so that an error is not thrown?
I'd prefer a solution using JSTL tags.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其放入
c:catch 中
标签。它将捕获任何抛出的Exception
为您服务。不过,我必须承认我不喜欢
c:catch
方法。它滥用异常来控制流程。如果可以的话,最好在 servlet 或 JavaBean 中借助 <代码>File#exists()(和ServletContext#getRealPath()
)。Put it in a
c:catch
tag. It will catch any thrownException
for you.I must however admit that I don't like the
c:catch
approach. It's abusing exceptions to control the flow. If you can, rather do this job in a servlet or JavaBean instead with help ofFile#exists()
(andServletContext#getRealPath()
).@BalusC 非常聪明,可能回答了这个问题。
然而,为了完整起见,标准 JSTL 中的任何内容都不会执行您想要的操作,但您当然可以创建自己的 EL 函数来用于执行检查。显然您需要为其编写 Java,但它不是内联在您的 JSP 中。
J2EE 1.4 教程中有一个关于创建您的自己的EL功能。
@BalusC is quite clever, and probably answers the question.
However, to be complete, nothing in the standard JSTL will do what you want, but you can certainly create your own EL functions that you can use to do the check. Obviously you'll need to write Java for it, but it's not inline within your JSPs.
The J2EE 1.4 Tutorial has a section on creating your own EL functions.