views:

411

answers:

2

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}" />   
...

How can I check if the file exists before trying to include it so that an error is not thrown?

I'd like to avoid using inline Java. Something using one of the JSTL tags is the preferred approach.

+2  A: 

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

BalusC
+1  A: 

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

Will Hartung