In a project using JSF, we have JavaScript files located here:
MyProject/view/javascript/*.js
In the xhtml file, I include these resources as
<script type="text/javascript" src="javascript/#{myBean.jsFileName}.js" />
This works fine, but it's possible that #{myBean.jsFileName}.js
doesn't exist, in which case I want to load "Default.js".
In myBean (or in the xhtml file itself), how can I first check for the existence of a js file before setting the #{myBean.jsFileName}
value? I've tried variations of this:
File f = new File("javascript/myFile.js");
if (!f.exists){ jsFileName="Default"};
But I don't think that's right. Am I on the right track?
You can use ExternalContext#getResource()
to obtain a web resource as URL
. It will return null
if resource doesn't exist. It takes a path relative to the web root and should preferably always start with /
.
So. this should do in bean:
String fullPath = "/view/javascript/myFile.js";
URL resource = FacesContext.getCurrentInstance().getExternalContext().getResource(fullPath);
if (resource == null) {
fullPath = "/view/javascript/default.js";
}
Or, equivalently, this in the view, which is IMO somewhat hacky:
<c:set var="available" value="#{not empty facesContext.externalContext.getResource(bean.fullPath)}" />
<script src="#{available ? bean.fullPath : bean.fullDefaultPath}" />
Unrelated to the concrete problem, if you were using JSF 2.x (at least Facelets, as implied by being able to use unified EL in template text in your code snippet), you should be using resource libraries with <h:outputScript>
. See also How to reference CSS / JS / image resource in Facelets template?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With