Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...