如何在不刷新我的网页的情况下在JSF(Primefaces)中重新加载图片

时间:2015-11-13 13:07:58

标签: jsf primefaces

我有一个小项目,从数据库中读取/搜索数据包括图片。我已将primefaces-5.3.jar添加到我的项目中,而我的问题是,当我将用户照片更改为另一个时,它不会立即显示我的更改,而我可以在用户记录中看到其他更改(更新)并且仅当我刷新网页我能看到另一张图片。请帮帮我这个

这是我的代码:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:p="http://primefaces.org/ui"
  xmlns:f="http://xmlns.jcp.org/jsf/core">
//....
<h:form  id="searchform"> 
<!--1 Form for searching    -->

    <br/>
    <br/>
    <h:form  id="searchform">
        <p:outputLabel value="type the key"/>
        <p:inputText value="#{personBean.searchinperson.searchAllUsingLikeOpSTRING}" required="true"  requiredMessage="Please Enter the key"/>


        <br/>
        <p:commandButton  value="Search by key"  icon="ui-icon-search" action="#{personBean.displaySearchedPeopleList()}"   update="searchform"/>

        <p:dataTable  id="searchdatatable_id"  value="#{personBean.listofSeachedPeople}"  var="person">

            <p:column headerText="PersonId">
                <p:outputLabel  value="#{person.personid}"/>
            </p:column>

            <p:column headerText="FirstName">
                <p:outputLabel  value="#{person.firstname}"/>
            </p:column>

            <p:column headerText="LastName">
                <p:outputLabel  value="#{person.lastname}"/>
            </p:column>

            <p:column headerText="Age">
                <p:outputLabel  value="#{person.age}"/>
            </p:column>

            <p:column headerText="UserName">
                <p:outputLabel  value="#{person.username}"/>
            </p:column>

            <p:column headerText="Password" >
                <p:outputLabel   value="#{person.password}"/>
            </p:column>

            <p:column headerText="DataAddTime" >
                <p:outputLabel   value="#{person.dataaddtime}"/>
            </p:column>

            <p:column  headerText="Person Photo">
                <p:graphicImage   value="#{personBeanApp.imageDisplay}"  alt="no image"  height="150"  width="150">
                   <f:param value="#{person.personid}" name="image_id"/>   
                </p:graphicImage>
            </p:column>

            <p:column  headerText="Modification">
                <p:commandLink  value="Modify"   actionListener="#{personBean.readPersonID(person)}"   oncomplete="PF('wdlgData').show();"  update=":dlgDataform"  />

            </p:column>

            <p:column  headerText="Delete" style=" color: red;">
                <p:commandLink  value="Delete Person"  actionListener="#{personBean.readPersonID(person)}"   oncomplete="PF('wdlgconfirmation').show();"   update=":dlgconfdelform"  />

            </p:column>



        </p:dataTable>

    </h:form>


<!-- Dialog for Modification  column -->

    <h:form  id="dlgDataform">

        <p:dialog  header="Data"  widgetVar="wdlgData" >

            <h:panelGrid  columns="2" cellpadding="5">


                <p:outputLabel for="modifyDlgPersonid_id" value="PersonID"/>
                <p:inputText  id="modifyDlgPersonid_id" value="#{personBean.person.personid}"  required="true" />





                <p:outputLabel  for="modifyDlgFirstname_id" value="FirstName"/>
                <p:inputText id="modifyDlgFirstname_id"  value="#{personBean.person.firstname}"  required="true" /> 





                <p:outputLabel  for="modifyDlgLastname_id" value="LastName"/>
                <p:inputText id="modifyDlgLastname_id" value="#{personBean.person.lastname}"  required="true"/>





                <p:outputLabel  for="modifyDlgAge_id" value="Age"/>
                <p:inputText  id="modifyDlgAge_id" value="#{personBean.person.age}" required="true"/>




                <p:outputLabel for="modifyDlgUsername_id" value="UserName"/>
                <p:inputText  id="modifyDlgUsername_id"  value="#{personBean.person.username}"  required="true"/>




                <p:outputLabel for="modifyDlgPassword_id"  value="Password"/>
                <p:inputText  id="modifyDlgPassword_id" value="#{personBean.person.password}"   required="true"/>



            </h:panelGrid>
            <p:outputLabel value="add/alter Picture"/>
            <p:fileUpload fileUploadListener="#{personBean.handleFileUploadForAdminModifyDlg}" mode="advanced" dragDropSupport="false"
                    update="adminModifyDlgUpload_msgs" sizeLimit="1000000" fileLimit="1" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
             <p:messages  id="adminModifyDlgUpload_msgs" for="adminModifyDlgPicUpload" showDetail="true" autoUpdate="true" closable="true" />

            <br/>
            <br/>
            <p:separator />
            <p:messages  for="dialogModAdmin" showDetail="true" autoUpdate="true" closable="true" />


            <br/>
            <p:commandButton  value="Modify"  actionListener="#{personBean.modificatePersonData()}"  update=":searchform:searchdatatable_id" />
            <h:outputText value="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" />
            <p:commandButton  value="Cancel/Close"  immediate="true"  oncomplete="PF('wdlgData').hide();"/>



        </p:dialog>



    </h:form>

PersonBean.java:

@ManagedBean
@SessionScoped

public class PersonBean {




private  List<Person> listofSeachedPeople;

public List<Person> getListofSeachedPeople() {
    return listofSeachedPeople;
}

public void setListofSeachedPeople(List<Person> listofSeachedPeople) {
    this.listofSeachedPeople = listofSeachedPeople;
}




public  void  displaySearchedPeopleList() throws Exception
{
        PersonDAO  dao;

        try{ 

                dao=new PersonDAO();
               listofSeachedPeople=dao.searchByAll(searchinperson);

              }
        catch(Exception ex){throw ex;}


}





 public void readPersonID(Person per) throws Exception{

    PersonDAO  dao;
    Person temp;
    try{
              dao=new PersonDAO();

              temp=dao.readID(per);

              if(temp!=null){ persId=temp.getPersonid();persPass=temp.getPassword();this.person=temp;   }

        }
    catch(Exception  ex){throw  ex;}


}




public void modificatePersonData() throws Exception{

    PersonDAO  dao;

    try{
        dao=new PersonDAO();


       if("personIdFree".equals(dao.IsPersonIdFreeExceptThis(person))   &&  "passwordFree".equals(dao.IsPasswordFreeExceptThis(person))){dao.modificate(person);FacesContext.getCurrentInstance().addMessage("dialogModAdmin", new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "The Data has been modified"));}
       else {FacesContext.getCurrentInstance().addMessage("dialogModAdmin", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "PersonID or Password is already in use"));}




       this.displaySearchedPeopleList();




    }
    catch(Exception ex){throw ex;}

}




public void handleFileUploadForAdminModifyDlg(FileUploadEvent event) throws Exception {


    try{
        if(event.getFile()!=null){

        uplf.setUploadedFile(event.getFile());

      person.setPersonimage(IOUtils.toByteArray(uplf.getUploadedFile().getInputstream()));  
    FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage("adminModifyDlgPicUpload", message);}


    }

    catch(Exception ex){throw ex;}
}

PersonDAO.java:

public void modificate(Person per) throws Exception {


    PreparedStatement pst;
     Date date = new Date();
    DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss");    

    try {
        this.connectDB();




        pst = this.getConn().prepareStatement("UPDATE person SET  personid=?,firstname=?, lastname=?, age=?, username=?, password=?,dataaddtime=?,personimage=? WHERE personid=? ");

        pst.setInt(1, per.getPersonid());
        pst.setString(2, per.getFirstname());
        pst.setString(3, per.getLastname());
        pst.setInt(4, per.getAge());
        pst.setString(5, per.getUsername());
        pst.setString(6, per.getPassword());
        pst.setString(7, df.format(date));
        pst.setBytes(8,per.getPersonimage());

        pst.setInt(9,PersonBean.getPersId());

        pst.executeUpdate();

    } catch (Exception ex) {
        throw ex;
    } finally {
        this.toClose();
    }

}



 public byte[] chosenPictureInBytes(int id) throws Exception{

PreparedStatement pst;
ResultSet rs;

byte[] byteArr =new byte[1048576];
try{
      this.connectDB();


  pst = this.getConn().prepareStatement("SELECT personimage FROM person  WHERE personid=? ");
  pst.setInt(1,id);

   rs = pst.executeQuery();

   while(rs.next()){
                 // byteArr=rs.getBytes("personimage");
                  Blob blobPic = rs.getBlob("personimage");
                  byteArr=blobPic.getBytes(1,(int) blobPic.length());

          }

}
catch(Exception ex){throw ex;}
finally{this.toClose();}

return byteArr;

}

PersonBeanApp.java:

@ManagedBean


 @ApplicationScoped

public class PersonBeanApp {


public StreamedContent   getImageDisplay() throws Exception{

     PersonDAO  dao;

     try{
     dao=new PersonDAO();


   FacesContext fc=FacesContext.getCurrentInstance();

    String id=fc.getExternalContext().getRequestParameterMap().get("image_id");

    if(fc.getCurrentPhaseId()==PhaseId.RENDER_RESPONSE){ return  new DefaultStreamedContent(); }


    byte[] imageInByteArray=dao.chosenPictureInBytes(Integer.parseInt(id));



   return new DefaultStreamedContent(new ByteArrayInputStream(imageInByteArray));


     }

     catch(Exception ex){throw ex;}


}

}

请帮帮我......

1 个答案:

答案 0 :(得分:0)

在我的情况下,我必须在模态对话框中有一个img标签,我在用户点击对话框上的提交按钮时更新了@form。

<p:dialog widgetVar="dlg7" id="showImage" closable="true" modal="true"     header="Edit Email Image" closeOnEscape="true" draggable="true" dynamic="true" >
        <p:ajax event="close" listener="#{emailConfigurationEditAction.handleCloseEditImage}" update=":emailConfiguration" />
        <h:form id="editImage">
            <div id="editImageDiv" align="center">
                <p:messages globalOnly="false" autoUpdate="true" id="messages"
                        rendered="true" closable="true">
                        <p:effect id="idar760" type="bounce" event="load" delay="500" />
                </p:messages>
                <h:panelGrid columns="2" width="500px;" id="editImageGrid" columnClasses="emailTemplatePadding,row1-padding">
                    <p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_NAME}" for="imageNameText" id="imageNameLable" />
                    <h:outputText value="#{emailConfigurationEditAction.editEmbeddedImage.cidname}" converter="upperCaseConverter" id="imageNameText" style="width:300px;" maxlength="20" validatorMessage="#{msg.EMAIL_INLINE_IMAGES_CIDNAME_VLDMSG}"/>
                    <p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_MIMETYPE}" for="imageMimeType" id="imagemimeLabel"/>
                    <p:selectOneMenu id="imageMimeType" value="#{emailConfigurationEditAction.editEmbeddedImage.mimeType}" style="width:310px">
                        <f:selectItem itemLabel="#{msg.DROP_SELECTONE }" itemValue="#{null}" />
                        <f:selectItems value="#{emailConfigurationEditAction.mimeTypeOptions}"/>
                    </p:selectOneMenu>
                    <p:outputLabel value="Uploaded Image:" id="imageUploadedLabel"/>
                    <img width="100" height="100" border="0" id="imageUploaded" src="data:image/jpg;base64,#{imageUtility.getImageAsString(emailConfigurationEditAction.editEmbeddedImage.imageByteArray)}" />
                    <!-- p:graphicImage value="#{emailImages.image}" id="imageUploaded" height="100px" width="100px" >
                        <f:param name="cidName" value="#{emailConfigurationEditAction.editEmbeddedImage.cidname}"/>
                    </p:graphicImage-->
                    <p:outputLabel value="#{msg.EMAIL_INLINE_IMAGE_UPLOAD}" for="imageUploader" id="imageUploaderLabel"/>
                    <p:fileUpload id="imageUploader" mode="advanced" dragDropSupport="true" fileLimit="1" update=":editImage" style="width:310px" label="#{msg.EMAIL_INLINE_UPLAOD_IMAGE}"
                        allowTypes="/(\.|\/)(gif|jpe?g|png)$/"  fileUploadListener="#{emailConfigurationEditAction.imageEditListener}" fileLimitMessage="#{msg.EMAIL_INLINE_IMAGES_FILELIMIT_VLDMSG}"/>
                </h:panelGrid>
                <p:commandButton value="#{msg.BTN_SUBMIT}" id="submitNewImage" action="#{emailConfigurationEditAction.updateEmbeddedImage}" process=":editImage" ajax="true" update="@form"/>
                <p:commandButton value="#{msg.BTN_CANCEL}" id="cancelEditImage" action="#{emailConfigurationEditAction.cancel}" immediate="true" ajax="true" process="@this"/>
            </div>
        </h:form>
    </p:dialog>

我的数据表看起来如下:

<p:dataTable  var="image" value="#{emailConfigurationEditAction.searchedImages}" id="dataTableImages" rendered="#{emailConfigurationEditAction.searchedImages!=null}" 
                     paginator="true" rows="10" paginatorPosition="top"
                        rowStyleClass="#{index%2==0?'row1Data':'row2Data'}" style="width:600px;"
                        styleClass="ui-citi-datatable-paginator"
                        rowClasses="row1Data,row2Data"
                        paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
                        currentPageReportTemplate="{currentPage} #{msg.LBL_OF} {totalPages}"
                        emptyMessage="#{msg.INFO_SEARCH_RESULT_EMPTY}" >
                    <p:column id="col1" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_NAME}" styleClass="centered" style="width:175px;">
                        #{image.cidname}
                    </p:column>
                    <p:column id="col2" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_MIMETYPE}" styleClass="centered" style="width:120px;">
                        #{image.mimeType}
                    </p:column>
                    <p:column id="col3" headerText="#{msg.EMAIL_INLINE_IMAGES_COLHDR_IMAGE}" styleClass="centered" style="width:120px;">
                        <img width="100" height="100" border="0" id="graphicImage3"
                                        src="data:image/jpg;base64,#{imageUtility.getImageAsString(image.imageByteArray)}" />

                        <!--p:graphicImage value="#{emailImages.image}" id="graphicImage3" height="100px" width="100px;">
                            <f:param name="cidName" value="#{image.cidname}"/>
                        </p:graphicImage-->
                    </p:column>
                    <p:column id="col4" headerText="" styleClass="centered" style="width:60px;">
                        <!-- h:commandButton image="/global/images/Delete_But_small.png" title="#{msg.LBL_EVENTEMAILMAPPING_DELETE_BUTTON}" immediate="true" value="#{msg.BTN_DELETE}" id="imgDelete"/>
                        <pe:tooltip for="imgDelete" value="#{msg.LBL_EVENTEMAILMAPPING_DELETE_BUTTON}" myPosition="left" atPosition="right"
                            showEffect="slideToggle" hideEffect="slideToggle" id="tooltip_delimg"/-->
                        <h:commandButton image="/global/images/Edit_But_small.png" title="#{msg.LBL_EVENTEMAILMAPPING_EDIT_BUTTON}" value="#{msg.BTN_EDIT}" id="imgEdit" action="#{emailConfigurationEditAction.editImage(image)}">
                            <p:ajax update=":editImage" oncomplete="PF('dlg7').show()" process="dataTableImages"/>                              
                        </h:commandButton>
                        <pe:tooltip for="imgEdit" value="#{msg.LBL_EVENTEMAILMAPPING_EDIT_BUTTON}" myPosition="left" atPosition="right"
                            showEffect="slideToggle" hideEffect="slideToggle" id="tooltip_edim"/>
                    </p:column>
                </p:dataTable>

当我使用grpahicImage时,我明白它不会因为它的设计方式而起作用