【问题标题】:Import javascript and css in head tag in a custom jsf component在自定义 jsf 组件的 head 标记中导入 javascript 和 css
【发布时间】:2011-01-28 13:58:34
【问题描述】:

如何在自定义jsf组件生成的html的head标签中导入javascript和css文件?我发现了一些关于为此目的使用资源的文章。

如(来源: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";

但是除了写在头标签之外,导入链接也写在我的组件代码中。 writeScriptResource() 方法在 encodeBegin 方法的开头被调用。 有谁知道如何做到这一点以避免在我的页面中注入内联脚本和样式?

提前致谢, 保罗·S.

【问题讨论】:

    标签: jsf resources custom-component


    【解决方案1】:

    我不知道您是否可以使用 JSF 2,但使用复合组件更容易使用 h:outputStylesheet 和 h:outputScript 包含资源。当页面被渲染时,资源将在 html 的头部。

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 2013-02-07
      • 2018-10-04
      • 2014-02-11
      相关资源
      最近更新 更多