How to obtain an InputStream of a public webcontent resource?

后端 未结 1 880
我在风中等你
我在风中等你 2020-12-12 03:52

I have a collection of images packaged in my WAR and I depict them in a using . The images are located in

相关标签:
1条回答
  • 2020-12-12 04:23

    Given this folder structure,

    YourProject
     |-- src
     |    `-- com
     |         `-- example
     |              `-- BackingBean.java
     |-- WebContent
     |    |-- META-INF
     |    |-- WEB-INF
     |    |-- resources
     |    |    `-- icons
     |    |         `-- foo.png
     |    `-- foo.xhtml
     :
    

    You can get it by either ExternalContext#getResourceAsStream() which takes webcontent-relative path:

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    InputStream input = externalContext.getResourceAsStream("/resources/icons/foo.png");
    // ...
    

    Or by Resource#getInputStream() wherein Resource is obtained from ResourceHandler#createResource() which takes a /resources-relative path:

    ResourceHandler resourceHandler = FacesContext.getCurrentInstance().getApplication().getResourceHandler();
    InputStream input = resourceHandler.createResource("icons/foo.png").getInputStream();
    // ...
    

    As to selecting the image and passing its path around, just do something like as follows:

    <h:graphicImage name="icons/foo.png">
        <f:ajax event="click" listener="#{bean.setImage(component.name)}" />
    </h:graphicImage>
    <h:graphicImage name="icons/bar.png">
        <f:ajax event="click" listener="#{bean.setImage(component.name)}" />
    </h:graphicImage>
    <h:commandButton value="submit" action="#{bean.saveImage}" />
    

    See also:

    • getResourceAsStream() vs FileInputStream
    • Where to place and how to read configuration resource files in servlet based application?
    • Maven and JSF webapp structure, where exactly to put JSF resources
    0 讨论(0)
提交回复
热议问题