ManagedBean在Primefaces中将null返回到graphicImage

时间:2012-11-30 18:49:12

标签: jsf-2 primefaces jboss7.x

我在Primefaces组件graphicImage中显示图像时遇到问题。

当我的MB是SessionScoped时,一切正常。但是当它是ViewScoped时,图像没有显示出来。

我可以保持SessionScoped,但是我的页面会在图像中上传/删除,而这些存储在PostgreSQL中(请,我的软件架构强迫我这样做)。问题是当我插入新图像或删除一个图像时,页面仍显示最后的值(未刷新的图像),直到我关闭浏览器并再次打开。我希望通过ViewScoped我可以重新加载页面,我的问题就解决了。

以下是该页面的快照:

                    <p:panel id="panelListFotoProduto" header="Fotos do Produto" toggleable="true" collapsed="false" closable="false"
                             toggleSpeed="500" widgetVar="panelListFotoProduto" visible="true" >
                        <p:dataTable id="listFotoProduto" paginatorPosition="bottom" value="#{produtoMB.listProdutoFoto}" 
                                     lazy="true" var="pf" selectionMode="single" paginator="true" rows="1"
                                     rowKey="#{pf.id}">
                            <p:column style="width: 100%" >
                                <h:panelGrid columns="1" cellpadding="4"> 
                                    <p:graphicImage id="imageProduto" value="#{produtoMB.getFoto(pf)}" onclick="dialogFotoProduto.show()"/>
                                    <p:commandButton value="Excluir" style="width: 100%;" update=":growl :formProduto:panelListFotoProduto" actionListener="#{produtoMB.removeFoto(pf)}"/>
                                </h:panelGrid>     
                            </p:column>
                            <f:facet name="footer">
                                <h:panelGrid columns="1" cellpadding="4"> 
                                    <p:commandButton value="Adicionar" style="width: 100%;" update=":growl :formProduto:panelListFotoProduto" actionListener="#{produtoMB.adicionarFoto()}"/>
                                    <h:outputText id="totalProdutos" style="font-weight:bold" value="Total de Fotos Cadastrados: #{produtoMB.listProdutoFoto.size() }"/>
                                </h:panelGrid>                                      
                            </f:facet>
                        </p:dataTable>
                    </p:panel>

这是我的MB:

@ManagedBean
@SessionScoped
public class ProdutoMB {

    private Produto       produto_atual      = new Produto();
    private Produto_Foto  produto_foto_atual = new Produto_Foto();

    private List<Produto>      listProduto         = null;    
    private List<Produto_Foto> listProdutoFoto     = null;
    private List<Produto_Foto> listProdutoFoto_all = null;

    private boolean adicionarFoto = false;
    private StreamedContent last;

    public Produto getProduto_atual(){
        return produto_atual;
    }    

    public void setProduto_atual(Produto produto) throws SQLException, IOException{        
        if(produto != null && produto_atual != null 
        && produto.getCd_produto().equals(produto_atual.getCd_produto())){
            return ;
        }
        produto_atual = produto;
        produto_foto_atual = null;        
        listProdutoFoto    = new ArrayList<>();

        int index = 0;
        System.out.println("List >> " + getListProdutoFoto_all());
        for(Produto_Foto p_f : getListProdutoFoto_all()){
            if(produto_atual.getCd_produto().equals(p_f.getCd_produto())){
                p_f.setId(index++);
                p_f.setContent(getFoto_b(produto_atual.getCd_empresa(), p_f.getCd_imagem()));
                listProdutoFoto.add(p_f);
            } 
        }

        if(listProdutoFoto.isEmpty()){
            Produto_Foto p_f = new Produto_Foto();
            p_f.setId(-1);
            p_f.setCd_produto(produto_atual.getCd_produto());
            p_f.setCd_empresa(produto_atual.getCd_empresa());
            p_f.setCd_imagem(-1);
            p_f.setContent(getFoto_b(produto_atual.getCd_empresa(), p_f.getCd_imagem()));
            listProdutoFoto.add(p_f);
        }       
    }

    public void setProduto_foto_atual(Produto_Foto produto_foto) {
        if(produto_foto != null && produto_foto_atual != null 
        && produto_foto.getCd_produto().equals(produto_foto_atual.getCd_produto())){
            return ;
        }
        produto_foto_atual = produto_foto;
    }

    public ProdutoMB(){
    }

    public void handleFileUpload(FileUploadEvent event) throws SQLException, IOException{
        if(event != null){            
            UploadedFile imagem_upload = event.getFile();

            byte[] buf = imagem_upload.getContents();
            BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(buf)));            

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write( image, "jpg", baos );
            baos.flush();
            buf = baos.toByteArray();
            baos.close();            

            BufferedImage scaledImage = Scalr.resize(image, 250);

            if(scaledImage != null){
                baos = new ByteArrayOutputStream();
                ImageIO.write( scaledImage, "jpg", baos );
                baos.flush();
                byte[] imageInByte = baos.toByteArray();
                baos.close();

                buf = imageInByte;
            }

            if(adicionarFoto){
                adicionarFoto = false;

                Produto_Foto p_f = new Produto_Foto();
                p_f.setId(listProdutoFoto.size());
                p_f.setCd_produto(produto_atual.getCd_produto());
                p_f.setCd_empresa(produto_atual.getCd_empresa());
                p_f.setCd_imagem(-1);
                p_f.setContent(buf);

                if(listProdutoFoto.size() == 1){
                    Produto_Foto p_f_aux = listProdutoFoto.get(0);
                    if(p_f_aux.getId() == -1){
                        p_f.setId(0);
                        listProdutoFoto.set(0, p_f);
                    } else {
                        listProdutoFoto.add(p_f);
                    }
                } else {
                    listProdutoFoto.add(p_f);
                }
                return;
            }

            if(produto_foto_atual != null){
                int index = produto_foto_atual.getId();
                if(index >= 0){
                    produto_foto_atual.setContent(buf);
                    listProdutoFoto.set(index, produto_foto_atual);
                } else if(index == -1){
                    produto_foto_atual.setContent(buf);
                    produto_foto_atual.setId(++index);
                    listProdutoFoto.set(index, produto_foto_atual);
                }
            }
        } 
    }

    public void adicionarFoto(){
        adicionarFoto = true;
        RequestContext.getCurrentInstance().execute("dialogFotoProduto.show()");
    }

    public void removeFoto(Produto_Foto produto_foto) throws SQLException, IOException{
        if(produto_foto == null){
            return ;
        }
        int index = produto_foto.getId();
        if(index >= 0){
            listProdutoFoto.remove(index);

            for(int i = 0; i < listProdutoFoto.size(); i++){
                Produto_Foto p_f = listProdutoFoto.get(i);
                if(p_f.getId() > index){
                    p_f.setId(p_f.getId() - 1);
                }
            }
        }
        if(listProdutoFoto.isEmpty()){
            Produto_Foto p_f = new Produto_Foto();
            p_f.setId(-1);
            p_f.setCd_produto(produto_atual.getCd_produto());
            p_f.setCd_empresa(produto_atual.getCd_empresa());
            p_f.setCd_imagem(-1);
            p_f.setContent(getFoto_b(produto_atual.getCd_empresa(), p_f.getCd_imagem()));
            listProdutoFoto.add(p_f);
        }    
    }

    public void removeFotoAtual(){
        if(produto_foto_atual == null){
            return ;
        }
        int index = produto_foto_atual.getId();
        if(index >= 0){
            listProdutoFoto.remove(index);

            for(int i = 0; i < listProdutoFoto.size(); i++){
                Produto_Foto p_f = listProdutoFoto.get(i);
                if(p_f.getId() > index){
                    p_f.setId(p_f.getId() + 1);
                }
            }
        }
    }

    public void removeFotoBanco(Produto_Foto pf_aux) throws SQLException{
        if(produto_atual == null){
            return ;
        }

        if(pf_aux == null){
            return ;
        }

        Integer cd_empresa = produto_atual.getCd_empresa();

        if(cd_empresa == null){
            return ;
        }

        Connection conn = null;
        Connection conn_p = null;
        PreparedStatement ps = null;
        ResultSet rs         = null;
        try {
            conn   = conectorImagemPostgreSQL.getConnection(); 
            conn_p = conectorPostgreSQL.getConnection();
            conn.setAutoCommit(false);

            ps = conn_p.prepareStatement(" DELETE FROM produto_foto WHERE cd_empresa = ? AND cd_produto = ? AND nm_foto = ? AND cd_imagem = ?;");                        
            ps.setInt(1, cd_empresa);
            ps.setString(2, produto_atual.getCd_produto());
            ps.setString(3, pf_aux.getNm_foto());
            ps.setInt(4, pf_aux.getCd_imagem());
            ps.executeUpdate();
            ps.close();
        } catch(Exception e){
            e.printStackTrace();
        } finally{
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            conn.commit();
        }
    }

    public void salvaFotoBanco() throws SQLException{
        if(produto_atual == null){
            return ;
        }

        if(listProdutoFoto == null || listProdutoFoto.isEmpty()){
            return ;
        }

        Integer cd_empresa = produto_atual.getCd_empresa();

        if(cd_empresa == null){
            return ;
        }

        Connection conn = null;
        Connection conn_p = null;
        PreparedStatement ps = null;
        ResultSet rs         = null;

        conn   = conectorImagemPostgreSQL.getConnection(); 
        conn_p = conectorPostgreSQL.getConnection();  

        ps = conn_p.prepareStatement(" DELETE FROM produto_foto WHERE cd_empresa = ? AND cd_produto = ?;");

        ps.setInt(1, cd_empresa);
        ps.setString(2, produto_atual.getCd_produto());
        ps.executeUpdate();
        ps.close();

        conn_p.commit();

        for(Produto_Foto p_f : listProdutoFoto){                       
            try {
                conn.setAutoCommit(false);
                if(p_f.getId() >= 0 && p_f.getCd_imagem() < 0){

                    ps = conn.prepareStatement("SELECT f_sequencial('IMAGEMLO', ?) as cd_imagem");
                    ps.setInt(1, cd_empresa);
                    rs = ps.executeQuery();
                    if (rs != null) {
                        while(rs.next()) {
                            p_f.setCd_empresa(produto_atual.getCd_empresa());
                            p_f.setCd_produto(produto_atual.getCd_produto());
                            p_f.setCd_imagem(rs.getInt(1));
                        }
                    }
                    byte[] b = p_f.getContentBytes();

                    BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(b)));            

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write( image, "jpg", baos );
                    baos.flush();
                    b = baos.toByteArray();
                    baos.close();            

                    BufferedImage scaledImage = Scalr.resize(image, 250);

                    if(scaledImage != null){
                        baos = new ByteArrayOutputStream();
                        ImageIO.write( scaledImage, "jpg", baos );
                        baos.flush();
                        byte[] imageInByte = baos.toByteArray();
                        baos.close();

                        b = imageInByte;
                    }
                    LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
                    int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
                    LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
                    obj.write(b);
                    obj.close();
                    ps = conn.prepareStatement(" INSERT INTO imagemlo(cd_empresa, cd_imagem, ds_imagem, by_imagem) "
                                                        + "VALUES (?, ?, ?, ?);");

                    String file_name = p_f.getCd_empresa() + "_" + 
                                p_f.getCd_produto() + "_" + 
                                p_f.getCd_imagem() + ".jpg";

                    ps.setInt(1, cd_empresa);
                    ps.setInt(2, p_f.getCd_imagem());
                    ps.setString(3, file_name);
                    ps.setLong(4, oid);
                    ps.executeUpdate();
                    ps.close();
                }
                ps = conn_p.prepareStatement(" INSERT INTO produto_foto(cd_empresa, cd_produto, nm_foto, cd_imagem) "
                                                    + "VALUES (?, ?, ?, ?);");

                String file_name = p_f.getCd_empresa() + "_" + 
                                p_f.getCd_produto() + "_" + 
                                p_f.getCd_imagem() + ".jpg";

                ps.setInt(1, cd_empresa);
                ps.setString(2, produto_atual.getCd_produto());
                ps.setString(3, file_name);
                ps.setInt(4, p_f.getCd_imagem());
                ps.executeUpdate();
                ps.close();
            } catch(Exception e){
                e.printStackTrace();
            } finally{
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                conn.commit();
            }
        }
        FacesMessage msg = new FacesMessage("Alterações salvas com sucesso.", "");  
        FacesContext.getCurrentInstance().addMessage(null, msg); 
    }

    public void editaFoto(Produto_Foto produto_foto){
        if(produto_foto != null){
            produto_foto_atual = produto_foto;
        }
    }

    public StreamedContent getFotoAtual() throws SQLException, IOException{
        if(produto_foto_atual != null){
            int index = produto_foto_atual.getId();
            if(index >= 0){
                last = listProdutoFoto.get(index).getContent();
            }
        }
        return last;
    }

    public StreamedContent getFoto(Produto_Foto produto_foto) throws SQLException, IOException{
        if(produto_foto != null){
            produto_foto_atual = produto_foto;

            int index = produto_foto.getId();
            if(index >= 0){
                last = listProdutoFoto.get(index).getContent();
            }

            if(index == -1){
                last = listProdutoFoto.get(0).getContent();
            }
        }

        if(last == null){
            last = (new DefaultStreamedContent(new ByteArrayInputStream(getFoto_b(produto_atual.getCd_empresa(), -1)), "image/jpeg", "img_padrao"));
        }
        return last;
    }

    public StreamedContent getFoto(Integer cd_empresa, Integer cd_imagem) throws SQLException, IOException{
        Usuario u = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("LoggedUser");

        if(u == null){
            System.out.println("Usuário é nulo");
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));
            return (new DefaultStreamedContent(fis, "image/jpeg", "img_padrao"));
        }

        if(produto_atual == null){
            System.out.println("Produto Atual é nulo");
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));
            return (new DefaultStreamedContent(fis, "image/jpeg", "img_padrao"));
        }

        if(cd_empresa == null){
            System.out.println("cd_empresa é nulo");
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));
            return (new DefaultStreamedContent(fis, "image/jpeg", "img_padrao"));
        }

        if(cd_imagem == null || cd_imagem < 0){
            System.out.println("cd_imagem é nulo ou menor que zero");
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));
            return (new DefaultStreamedContent(fis, "image/jpeg", "img_padrao"));
        }

        Connection        conn = null;
        PreparedStatement   ps = null;
        ResultSet           rs = null;

        try {        
            conn = conectorImagemPostgreSQL.getConnection();  
            conn.setAutoCommit(false);
            LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

            ps = conn.prepareStatement("SELECT ds_imagem, by_imagem FROM imagemlo WHERE cd_empresa = ? AND cd_imagem = ?");
            ps.setInt(1, cd_empresa);
            ps.setInt(2, cd_imagem);

            rs = ps.executeQuery();
            if (rs != null) {
                while(rs.next()) {

                    String ds_imagem = rs.getString("ds_imagem");   
                    int oid = rs.getInt("by_imagem");

                    LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

                    //read the data
                    byte buf[] = new byte[obj.size()];
                    obj.read(buf, 0, obj.size());
                    obj.close();

                    BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(buf)));            

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write( image, "jpg", baos );
                    baos.flush();
                    buf = baos.toByteArray();
                    baos.close();            

                    BufferedImage scaledImage = Scalr.resize(image, 250);

                    if(scaledImage != null){
                        baos = new ByteArrayOutputStream();
                        ImageIO.write( scaledImage, "jpg", baos );
                        baos.flush();
                        byte[] imageInByte = baos.toByteArray();
                        baos.close();

                        buf = imageInByte;
                    }
                    return (new DefaultStreamedContent(new ByteArrayInputStream(buf), "image/jpeg", ds_imagem));
                }
            }
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            return (new DefaultStreamedContent(fis, "image/jpeg", "img_padrao"));
        } finally{
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            conn.commit();
        }
    }    

    public byte[] getFoto_b(Integer cd_empresa, Integer cd_imagem) throws SQLException, IOException{
        Usuario u = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("LoggedUser");

        if(u == null){
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024]; 
            while (fis.read(buffer) != -1) out.write(buffer); 

            return out.toByteArray();
        }

        if(produto_atual == null){
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            while (fis.read(buffer) != -1) out.write(buffer); 

            return out.toByteArray();
        }

        if(cd_empresa == null){
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024]; 
            while (fis.read(buffer) != -1) out.write(buffer); 

            return out.toByteArray();
        }

        if(cd_imagem == null || cd_imagem < 0){
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024]; 
            while (fis.read(buffer) != -1) out.write(buffer); 

            return out.toByteArray();
        }

        Connection        conn = null;
        PreparedStatement   ps = null;
        ResultSet           rs = null;

        try {        
            conn = conectorImagemPostgreSQL.getConnection();  
            conn.setAutoCommit(false);
            LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

            ps = conn.prepareStatement("SELECT ds_imagem, by_imagem FROM imagemlo WHERE cd_empresa = ? AND cd_imagem = ?");
            ps.setInt(1, cd_empresa);
            ps.setInt(2, cd_imagem);

            rs = ps.executeQuery();
            if (rs != null) {
                while(rs.next()) {

                    String ds_imagem = rs.getString("ds_imagem");   
                    int oid = rs.getInt("by_imagem");

                    LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

                    //read the data
                    byte buf[] = new byte[obj.size()];
                    obj.read(buf, 0, obj.size());
                    obj.close();
                    BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(buf)));            

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write( image, "jpg", baos );
                    baos.flush();
                    buf = baos.toByteArray();
                    baos.close();            

                    BufferedImage scaledImage = Scalr.resize(image, 250);

                    if(scaledImage != null){
                        baos = new ByteArrayOutputStream();
                        ImageIO.write( scaledImage, "jpg", baos );
                        baos.flush();
                        byte[] imageInByte = baos.toByteArray();
                        baos.close();

                        buf = imageInByte;
                    }
                    return buf;
                }
            }
            FileInputStream fis = new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("image_not_found.png"));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024]; 
            while (fis.read(buffer) != -1) out.write(buffer); 

            return out.toByteArray();
        } finally{
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            conn.commit();
        }
    }    

    public void save() throws SQLException{
        salvaFotoBanco();
    }

    public List<Produto> getListProduto() {

        Usuario u = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("LoggedUser");

        if(u == null){
            return null;
        }        

        Integer cd_empresa = u.getCd_empresa();

        if(cd_empresa == null){
            return null;
        }

        if(listProduto == null){
            listProduto = getProduto(cd_empresa);
        }

        return listProduto;
    }

    public List<Produto_Foto> getListProdutoFoto_all() {
        if(listProdutoFoto_all == null){
            listProdutoFoto_all = getProduto_Foto(produto_atual.getCd_empresa());
        }
        return listProdutoFoto_all;
    }

    /**
     * Methods to get/set data in the DB...
     */
}

如果我可以使用SessionScoped重新加载内容,那就更好。

感谢您的帮助。

我正在使用JBOSS 7,Primefaces 3.4.2

[]中 威廉·伯坦

2 个答案:

答案 0 :(得分:16)

了解<p:graphicImage> StreamedContent的工作原理非常重要。 <p:graphicImage value>背后的属性对于每个单独的图像基本上都要在两个完全独立的HTTP请求中查阅。

第一个HTTP请求(执行所有JSF的工作,因此负责生成包含<img>标签的HTML代码)将基本上咨询该属性,以确定它返回的图像类型(例如StringStreamedContent),以便可以内联/自动生成正确的URL。请注意,如果StreamedContent,则图片的内容已被阅读。 HTML图像不是那样工作的:它不是在同一个HTTP请求中内联它们的网络服务器,而是在另一个HTTP请求中单独下载它的web浏览器。

当使用StreamedContent时,则第二个HTTP请求(当需要根据<img>元素的URL下载具体图像文件以便显示时,webbrowser会触发该请求它在HTML文档中的所需位置)将基本上再次咨询该属性以便下载图像内容。

视图范围bean通过隐藏的输入字段javax.faces.ViewState绑定到特定的JSF视图。如果HTTP请求中没有这个(或者具有不同的值),那么基本上就是完全不同的视图。因此,对于那些图像请求,不会重用相同的视图范围bean实例。每个图像请求都会获得一个全新的视图范围bean实例,其所有属性都设置为默认值。会话范围的bean基本上与客户端和服务器之间当前建立的HTTP会话一样长,所以同样的bean实例将被重用于那些图像请求,所以它只是这样工作。

要解决您的具体问题,最好是创建一个应用程序,或者请求scoped bean,它通过ID作为请求参数获取图像。这样,您也不需要同时使用数十或数百个图像污染会话(这样只会在查看相同图像的多个并发用户时浪费服务器内存)。您只需要拥有数据表的图像标识符列表,并通过单独的应用程序范围bean提供图像。

另见:

答案 1 :(得分:0)

我有一个类似的&#34; OP的问题,我来到这里(以及BalusC的许多其他答案)。

BalusC解释像往常一样完美,但是如果像我和OP那样,你是如何严格限制的?在我的情况下:bean必须是ViewScope,存储在bean中的图像字节,上传后字节立即刷新&#34; ajaxely&#34;,你不能再根据属性(如ID)检索图像,并从数据库中获取它。 一般情况下,任何时候您有一次性生成的图像(验证码?)或图像以ajaxely(上传的图像?用户修改的图像?)。

我知道,对于这种富含ajax的应用程序,JSF / PrimeFaces并不是最好的框架,但是应用程序完全是用PrimeFaces编写的,所以......也许你想坚持使用PF,看看是否有可能找到解决方案

你可以使用ajax组件和创造力的组合来做到这一点,即remoteCommand,一些JS,以及我要链接的一堆StackOverflow答案。

首先,您需要调用remoteCommand。我是在&#34; onupload&#34; fileUploader的事件(与此answer类似),以及文档就绪时间(对于生成的图像)​​:

<p:fileUpload fileUploadListener="#{bean.handleFileUpload}"
              oncomplete="displayImageBegin();"

displayImageBegin只需调用remoteCommand:

function displayImageBegin() {
    if (typeof(getImage) == "function")
        getImage();
}

<p:remoteCommand name="getImage" action="#{bean.getImage()}"
                 oncomplete="displayImageEnd(xhr, status, args);"
                 style="display: none;" />

在bean端,getImage函数只返回图像字节。 这里有两个选项:对img src使用内联,base64编码(请参阅this answerthis one),或者只返回和修改流并将其放入canvas 。第二个选项更灵活,适用于更大的图像(我的图像很小,大小也受控制,因此base64编码很好):

您需要完全控制XHR答案的格式,例如answer(顺便说一下,我同意这是滥用JSF作为REST服务;将此代码视为一个有趣的实验):

public void getImage() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/text");
    externalContext.setResponseCharacterEncoding("UTF-8");

    if (getCurrentImagePresent()) {
        String base64Image = Base64.getEncoder().encodeToString(yourByteArray);
        externalContext.getResponseOutputWriter().write(base64Image);
    }
    else {
        externalContext.setResponseStatus(404);
    }
    facesContext.responseComplete();
}

remoteCommand oncomplete事件将从这个bean函数返回的数据连接到我们的JS,就像在this answer中一样:

function displayImageEnd(xhr, status, args) {
    if (xhr.status == 200) {
        $('#previewCurrentImage').attr("src", "data:image/png;base64," + xhr.responseText);
    }
}

(当然,你需要在你的xhtml中使用正确的img标签)

为什么这样做?答案是here

  

@ViewScoped bean与JSF视图完全一样长。   [...]

     

因此,@ richScoped bean在rich中特别有用   启用Ajax的视图,需要记住(更改的)视图状态   跨Ajax请求。

图像的字节数组是作为bean创建的一部分生成的,和/或作为对页面上的ajax操作的响应生成的;然后它可以被页面上的任何其他ajax动作检索,因为它将击中相同的ViewScoped bean。

这是一个在我的案例中起作用的解决方案;我一般不推荐它,但如果你的约束非常相似,你可以做点什么......类似! :)

我只是想分享它,因为它可能非常适合OP问题(或者正在寻找类似问题的人),并且它是一个很好的答案的好拼贴。