Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check if a file exists before including/importing it in 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?

I'd prefer a solution using JSTL tags.

like image 563
qodeninja Avatar asked Apr 12 '10 19:04

qodeninja


1 Answers

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

like image 136
BalusC Avatar answered Oct 04 '22 18:10

BalusC