在 JSP 中包含/导入文件之前,如何检查文件是否存在? [英] How can you check if a file exists before including/importing it in JSP?
问题描述
假设 requestScope.importMe 需要一个 JSP 文件的路径
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?
我更喜欢使用 JSTL 标签的解决方案.
I'd prefer a solution using JSTL tags.
推荐答案
放在 c:catch
标签.它将捕获任何抛出的 Exception
给你.
Put it in a c:catch
tag. It will catch any thrown Exception
for you.
<c:catch var="e">
<c:import url="${url}" />
</c:catch>
<c:if test="${!empty e}">
Error: ${e.message}
</c:if>
但是我必须承认我不喜欢 c:catch
方法.它滥用异常来控制流程.如果可以,最好在 servlet 或 JavaBean 中完成这项工作,而不是在 <代码>File#exists()(和ServletContext#getRealPath()
).
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 of File#exists()
(and ServletContext#getRealPath()
).
这篇关于在 JSP 中包含/导入文件之前,如何检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!