小编典典

在JSP中包含/导入文件之前,如何检查文件是否存在?

jsp

假设 requestScope.importMe 期望一个JSP文件的路径

<c:choose>
    <c:when test="${!empty requestScope.importMe && fileExists(requestScope.importMe) }">
    <c:import url="${requestScope.importMe}" />   
    ...
</c:choose>

如何在尝试包含文件之前检查文件是否存在,以免引发错误?

我希望使用JSTL标签的解决方案。


阅读 402

收藏
2020-06-08

共1个答案

小编典典

将其放在c:catch标签中。它会抓住任何抛出Exception给您的东西。

<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()

2020-06-08