How to import a javascript and a css file in head tag of a html generated by a custom jsf component? I've found some articles about using resources for this purpose.
As in (source: http://technology.amis.nl/blog/6047/creating-a-custom-jsf-12-component-with-facets-resource-handling-events-and-listeners-valueexpression-and-methodexpression-attributes):
protected void writeScriptResource(
FacesContext context,
String resourcePath) throws IOException
{
Set scriptResources = _getScriptResourcesAlreadyWritten(context);
// Set.add() returns true only if item was added to the set
// and returns false if item 开发者_运维知识库was already present in the set
if (scriptResources.add(resourcePath))
{
ViewHandler handler = context.getApplication().getViewHandler();
String resourceURL = handler.getResourceURL(context, SCRIPT_PATH +resourcePath);
ResponseWriter out = context.getResponseWriter();
out.startElement("script", null);
out.writeAttribute("type", "text/javascript", null);
out.writeAttribute("src", resourceURL, null);
out.endElement("script");
}
}
private Set _getScriptResourcesAlreadyWritten(
FacesContext context)
{
ExternalContext external = context.getExternalContext();
Map requestScope = external.getRequestMap();
Set written = (Set)requestScope.get(_SCRIPT_RESOURCES_KEY);
if (written == null)
{
written = new HashSet();
requestScope.put(_SCRIPT_RESOURCES_KEY, written);
}
return written;
}
static private final String _SCRIPT_RESOURCES_KEY =
ShufflerRenderer.class.getName() + ".SCRIPTS_WRITTEN";
However besides writing in head tag, the import link is also write in my component code. The method writeScriptResource() is called in the beginning of encodeBegin method. Does anyone know how to do that in order to avoid inject inline scripts and styles in my page?
Thanks in advance, Paulo S.
I don't know if you can use JSF 2 but with composite components is easier to include resources using h:outputStylesheet and h:outputScript. When the page is rendered, resources will be in the head of the html.
精彩评论