16

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.

qodeninja
  • 10,946
  • 30
  • 98
  • 152

2 Answers2

22

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

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi @BalusC! I'm also searching for an implementation like that one given in your answer. I search on SO posts, but I think your answer is the most easy way to implement my needs and I'm not sure to re-make a question about something already asked. I need to import in a jstl a dynamic url: I try to load the url of a specific region (eg: ./3/myJspx.jspx, and in case file cannot be found, it fallback to default region jspx: ./myJspx.jspx.. Given that much time has passed by your answer, meanwhile, have you came up with any other solution or have you got any other hint? – gipinani Jul 07 '14 at 21:13
4

@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
  • 115,893
  • 19
  • 128
  • 203
  • Details on making your own java are explained in this stackOverflow question... http://stackoverflow.com/questions/16788790/include-css-file-in-jsp-only-if-it-exist – Joris Kroos Nov 07 '13 at 10:32
  • @WillHartung: The section link above no longer drills down to the section you were referring to (I think). Can you include the main part of the answer in the question if it is not too big, or fix the link? – StackExchange What The Heck Aug 20 '14 at 11:04