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

发布于 2024-08-28 18:29:33 字数 342 浏览 1 评论 0原文

假设 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沙沙粒小 2024-09-04 18:29:33

将其放入 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())。

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>

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

是你 2024-09-04 18:29:33

@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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文