在JSP中包含/导入文件之前,如何检查文件是否存在? [英] How can you check if a file exists before including/importing it in JSP?

查看:94
本文介绍了在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:捕获 标记。它将捕获任何抛出的 异常

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆