Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if JSF resource exists before loading view

Tags:

javascript

jsf

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?

like image 689
Joe Avatar asked Nov 25 '13 15:11

Joe


1 Answers

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:

  • getResourceAsStream() vs FileInputStream

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?

like image 140
BalusC Avatar answered Sep 24 '22 04:09

BalusC