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

qod*_*nja 16 import jsp jstl file-exists

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

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

如何在尝试包含该文件之前检查该文件是否存在,以便不抛出错误?

我更喜欢使用JSTL标签的解决方案.

Bal*_*usC 22

把它放在c:catch标签中.它会抓住任何抛出Exception的东西.

<c:catch var="e">
    <c:import url="${url}" />
</c:catch>
<c:if test="${!empty e}">
    Error: ${e.message}
</c:if>
Run Code Online (Sandbox Code Playgroud)

但我必须承认,我不喜欢这种c:catch做法.它滥用例外来控制流量.如果可以的话,而是在(和)的帮助下在servlet或JavaBean中完成这项工作.File#exists()ServletContext#getRealPath()