42

<h:graphicimage>JSFタグまたはHTMLタグを使用して、Webアプリケーションのデプロイフォルダーの外にある画像を表示する必要があります<img>。どうすればそれを達成できますか?

4

4 に答える 4

78

要するに、パブリックURLでアクセスできる必要があります。したがって、は、URIなどではなく、<img src>最終的にhttp://URIを参照する必要がありfile://ます。最終的に、HTMLソースはエンドユーザーのマシンで実行され、画像はHTMLソースの解析中にWebブラウザーによって個別にダウンロードされます。Webブラウザがfile://などのURIを検出すると、WebブラウザC:\path\to\image.pngのイメージではなく、エンドユーザー自身のローカルディスクファイルシステムでイメージを検索します。WebブラウザがWebサーバーとは物理的に異なるマシンで実行されている場合、これは明らかに機能しません。

これを実現するには、いくつかの方法があります。

  1. 画像フォルダを完全に制御できる場合は、すべての画像を含むフォルダをドロップするだけです。たとえば、Tomcatの場合はフォルダ、GlassFishの場合はフォルダ/imagesなど、servletcontainerのデプロイフォルダに直接ドロップします。これ以上の構成は必要ありません。/webapps/domains/domain1/applications


  2. または、これらのイメージを含むフォルダーの絶対ディスクファイルシステムの場所を指す新しいWebアプリケーションコンテキストをサーバーに追加します。その方法は、使用するコンテナによって異なります。以下の例では、画像がにあり、http://.../images/path/to/imagesを介して画像にアクセスすることを前提としています。

    Tomcatの場合、Tomcatの/conf/server.xml内部に次の新しいエントリを追加します<Host>

    <Context docBase="/path/to/images" path="/images" />
    

    GlassFishの場合は、次のエントリを追加します/WEB-INF/glassfish-web.xml

    <property name="alternatedocroot_1" value="from=/images/* dir=/path/to" />
    

    WildFlyの場合、...内<host name="default-host">に次のエントリを追加します。/standalone/configuration/standalone.xml

    <location name="/images" handler="images-content" />
    

    ...そして上記<handlers>とまったく同じエントリのさらに下:<subsystem><location>

    <file name="images-content" path="/path/to/images" />
    

  3. または、Servletディスクから応答にイメージをストリーミングするを作成します。

    @WebServlet("/images/*")
    public class ImageServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String filename = request.getPathInfo().substring(1);
            File file = new File("/path/to/images", filename);
            response.setHeader("Content-Type", getServletContext().getMimeType(filename));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
        }
    }
    

    OmniFacesを使用する場合は、FileServletヘッド、キャッシング、および範囲のリクエストも考慮されるため、が役立つ場合があります。


  4. または、Beanプロパティの戻りをサポートするOmniFaces<o:graphicImage>byte[]を使用するか、次のようにしますInputStream

    @Named
    @ApplicationScoped
    public class Bean {
    
        public InputStream getImage(String filename) {
            return new FileInputStream(new File("/path/to/images", filename));
        }
    }
    

  5. または、PrimeFaces固有のを返すBeanメソッドをサポートするPrimeFaces<p:graphicImage>StreamedContentを使用します。

    @Named
    @ApplicationScoped
    public class Bean {
    
        public StreamedContent getImage() throws IOException {
            FacesContext context = FacesContext.getCurrentInstance();
    
            if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
                // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
                return new DefaultStreamedContent();
            }
            else {
                // So, browser is requesting the image. Return a real StreamedContent with the image bytes.
                String filename = context.getExternalContext().getRequestParameterMap().get("filename");
                return new DefaultStreamedContent(new FileInputStream(new File("/path/to/images", filename)));
            }
        }
    }
    

最初の方法とTomcatおよびWildFlyのアプローチでは、画像はhttp://example.com/images/filename.extで入手できるため、次のようにプレーンHTMLで参照できます。

<img src="/images/filename.ext" />

2番目と3番目の方法でのGlassFishアプローチの場合、画像はhttp://example.com/context/images/filename.extで利用できるため、次のようにプレーンHTMLで参照できます。

<img src="#{request.contextPath}/images/filename.ext" />

またはJSFでは次のようになります(コンテキストパスは自動的に先頭に追加されます)

<h:graphicImage value="/images/filename.ext" />

4番目の方法でのOmniFacesアプローチについては、次のように参照してください。

<o:graphicImage value="#{bean.getImage('filename.ext')}" />

5番目の方法でのPrimeFacesアプローチについては、次のように参照してください。

<p:graphicImage value="#{bean.image}">
    <f:param name="filename" value="filename.ext" />
</p:graphicImage>

この例#{bean}@ApplicationScoped、基本的にステートレスサービスを表しているためです。それを作成することもできますが@RequestScoped、その場合、Beanはすべてのリクエストで無料で再作成されます。@ViewScopedブラウザが画像をダウンロードする必要がある時点で、サーバーはJSFページを作成しないため、作成できません。あなたはそれを作ることができます@SessionScoped、しかしそれからそれは無料でメモリに保存されます。

参照:

于 2010-12-28T05:47:06.973 に答える
2

<h:graphicImage>またはタグを使用して必要なものを実現するに<img>は、外部パスをWebアプリのコンテキストにマップするためにTomcatv7エイリアスを作成する必要があります。

そのためには、Webアプリのコンテキストを指定する必要があります。最も簡単なのは、次の内容でMETA-INF/context.xmlファイルを定義することです。

<Context path="/myapp" aliases="/images=/path/to/external/images">
</Context>

<h:graphicImage次に、Tomcatサーバーを再起動した後、次のように>または<img>タグを使用してイメージファイルにアクセスできます。

<h:graphicImage value="/images/my-image.png">

また

<img src="/myapp/images/my-image.png">

*コンテキストパスはタグには必要ですが、


HTTP GETメソッドを介して画像を使用可能にする必要がない場合の別の可能なアプローチは、Primefaces<p:fileDownload>タグを使用することです(commandLinkまたはcommandButtonタグを使用-HTTP POSTメソッド)。

フェイスレット:

<h:form>
  <h:commandLink id="downloadLink" value="Download">  
    <p:fileDownload value="#{fileDownloader.getStream(file.path)}" />  
</h:commandLink>
</h:form

あなたの豆で:

@ManagedBean
@ApplicationScope
public class FileDownloader {

    public StreamedContent getStream(String absPath) throws Exception {
        FileInputStream fis = new FileInputStream(absPath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        StreamedContent content = new DefaultStreamedContent(bis);
        return content;
       }
    }
}
于 2013-04-30T05:18:05.497 に答える
1

PrimeFacesでは、次の方法でBeanを実装できます。

private StreamedContent image;

public void setImage(StreamedContent image) {
    this.image = image;
}

public StreamedContent getImage() throws Exception {
    return image;
}

public void prepImage() throws Exception {
File file = new File("/path/to/your/image.png");
InputStream input = new FileInputStream(file);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
setImage(new DefaultStreamedContent(input,externalContext.getMimeType(file.getName()), file.getName()));
}

HTMLフェイスレットの場合:

<body onload="#{yourBean.prepImage()}"></body> 
<p:graphicImage value="#{youyBean.image}" style="width:100%;height:100%" cache="false" >
</p:graphicImage>

graphicsImageコンポーネントで属性cache="false"を設定することをお勧めします。

于 2018-06-12T21:57:09.403 に答える
-2

JSPでは

<img src="data:image/jpeg;base64,
<%= new String(Base64.encode(Files.readAllBytes(Paths.get("C:\\temp\\A.jpg"))))%>"/>

パッケージは、、com.sun.jersey.core.util.Base64です。java.nio.file.Pathsjava.nio.file.Files

于 2014-12-15T15:32:16.160 に答える