你可以使用backbean jsf outputscript组件来做,当你使用jsf EL里面的javascript代码是正常的有多个请求问题,因为一个是静态和其他动态。
您可以将javascript代码作为函数放在一个js文件中的resource / js文件夹中,并使用类似的Managed bean调用该函数:
UIOutput output = new UIOutput();
output.setRendererType("javax.faces.resource.Script");
// JS FILE NAME DEFINED IN resource/js folder is put here ( example: myscript.js):
output.getAttributes().put("name", "myscript.js");
output.getAttributes().put("library", "js");
facesContext.getViewRoot().addComponentResource(facesContext, output, "form");
UIOutput script = (UIOutput) facesContext.getApplication()
.createComponent(facesContext,
JAVAX_FACES_OUTPUT_COMPONENT_TYPE,
JAVAX_FACES_TEXT_RENDERER_TYPE);
UIOutput outputScript = (UIOutput) facesContext.getApplication()
.createComponent(facesContext,
JAVAX_FACES_OUTPUT_COMPONENT_TYPE,
DEFAULT_SCRIPT_RENDERER_TYPE);
/** AT HERE YOU SHOULD CALL YOUR JAVA SCRIPT FUNCTION WITH THE PARAMETERS OF YOUR BACK BEAN
let's say that you have created something like that:
function addToLocalStorage(ville){
if(localStorage['ville'] == null || localStorage['date']==null){
localStorage.setItem('date',new Date());
localStorage.setItem('ville',ville});
}
}
So you're going to call the function from backbean like that:
*/
String ville = villeBean.listeVilles();
script.setValue("addToLocalStorage(" + ville + ")");
script.setTransient(true);
script.setId(facesContext.getViewRoot().createUniqueId());
outputScript.getChildren().add(script);
outputScript.setTransient(true);
outputScript.setId(facesContext.getViewRoot().createUniqueId());
facesContext.getViewRoot().addComponentResource(facesContext,
outputScript, TARGET_ATTR);
其他选项是使用Primefaces套件中的RequestContext,这样你就可以从JSF托管bean调用javascript函数:
RequestContext.getCurrentInstance().execute("myfunction()");