简体   繁体   中英

Serving javascript/jsf resources from a jsf app

I have a "/js/ajax-error.js" file that I would to serve in a "richfaces way" as follows: "/js/ajax-error.js.jsf" so that I use that kind of jsf variables in my js file: "#{facesContext.externalContext.requestContextPath}" .

Is that possible? I have tried prefixing my js file with xhtml: it does not work.

I use richfaces + jsf 2.0 + servlet 3.0

Can anyone please help?

(added) Is there not a clean JSF way to achieve the desired effect?

It is possible to do that, but I strongly suggest that you don't. Keep your JavaScript clean and cacheable.

A common pattern used to arrange for server-side data to be available to JavaScript is to drop values into "data-" attributes on appropriate parts of the HTML. For example, "global" information (say, stuff about the user's session, like user name, company name, etc) can be attached to the <body> :

<body data-username='John Phillip Sousa' data-registered='05 Jul 1903'>

Now the JavaScript can find out the username and registration date just by grabbing the data attributes off the <body> tag. edit like this:

var body = document.getElementsByTagName('body')[0];
var username = body.getAttribute("data-username");
var registrationDate = body.getAttribute("data-registered");

If your sole purpose is to serve it "the Richfaces way" (it's actually the JSF 2.0 way), then use <h:outputScript> . Put the file in /resources/js/ajax-error.js of public webcontent (the main path /resources is mandatory and its name cannot be changed). Then reference it as follows:

<h:outputScript name="js/ajax-error.js" />

Regardless of its location in the template, it'll be generated into the HTML <head> like follows assuming that your FacesServlet is mapped on *.jsf :

<script type="text/javascript" src="/contextname/javax.faces.resource/js/ajax-error.js.jsf"></script>

But that doesn't offer you EL support! You won't be able to use #{} in that script. Only in stylesheets which are included by <h:outputStylesheet> the #{} is supported in order to locate background images the JSF 2.0 #{resource['logo.png']} way, but nothing more than that.

In your particular case, I'd rather reference #{facesContext.externalContext.requestContextPath} (or its shorter and more popular counterpart #{request.contextPath} ) in the HTML <base> tag or some global JS variable or the HTML data attribute. If set as <base> , all relative links will be relative to it, also in JS.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM