7

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Joe
  • 103
  • 1
  • 5
  • That did it. I tried something similar before but didn't get it quite right. I was helpful to see my particular example. – Joe Nov 26 '13 at 16:43

1 Answers1

11

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

See also:


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?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • That did it. I tried something similar before but didn't get it quite right. I was helpful to see my particular example. – Joe Nov 26 '13 at 16:44