2011-11-14 1 views
0

사진을 업로드하고 미리 볼 수있는 페이지를 만들고 있습니다. 업로드와 미리보기가 잘 동작합니다. 하지만 문제는 이미지를 업로드 한 다음 미리보고 나서 이미지 업로드 페이지로 돌아 가면 이미지가 사라진다는 것입니다. 그때 사라 이미지를 미리보기 한 후 다시이 페이지에 올 때 여기 내 코드페이지 리디렉션 사이의 상태를 유지하는 방법 JSf 2.0

<h:panelGrid columns="4" 
       border="" 
       width="20%" 
       style="position: absolute; top: 50px;" 
       columnClasses="asteriskColumns, nameColumns" > 

       <h:outputText value="*" /> 
       <h:outputText value="Map: " /> 
       <p:fileUpload id="cityMap" 
          description="Image" 
          update="mapImage messages" 
          allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
          auto="true" 
          fileUploadListener="#{cityDetail.imageUpload}" > 

       </p:fileUpload> 

       <p:graphicImage id="mapImage" 
           value="#{cityDetail.imagePath}" 
           width="80" 
           height="50" 
           cache="false" /> 

       <h:outputText value="*" /> 
       <h:outputText value="Image1: " /> 
       <p:fileUpload id="cityImage1" 
          description="Image" 
          update="city_Image1 messages" 
          allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
          auto="true" 
          fileUploadListener="#{cityDetail.imageUpload}" > 

       </p:fileUpload> 

       <p:graphicImage id="city_Image1" 
           value="#{cityDetail.imagePath}" 
           width="80" 
           height="50" 
           cache="false" /> 



       <h:outputText value="*" /> 
       <h:outputText value="Image2: " /> 
       <p:fileUpload id="cityImage2" 
          description="Image" 
          update="city_Image2 messages" 
          allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
          auto="true" 
          fileUploadListener="#{cityDetail.imageUpload}" > 

       </p:fileUpload> 

       <p:graphicImage id="city_Image2" 
           value="#{cityDetail.imagePath}" 
           width="80" 
           height="50" 
           cache="false" /> 

것은 여기 지금 내 콩

@ManagedBean 
@ViewScoped 
@SessionScoped 
public class CityDetail { 

    private StreamedContent image; 
    private ArrayList images; 
    private ArrayList imageNames; 
    private String imagePath = "/resources/images/Untitled.jpg"; 
    private String imagePath1 = "/resources/images" + "/"; 

    public CityDetail() { 

     images = new ArrayList(); 
     images.add(null); 
     images.add(null); 
     images.add(null); 
     images.add(null); 
     images.add(null); 

     imageNames = new ArrayList(); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 

    // Getting session ID from seession variable that is set in the City_Review Page 
    cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString()); 

     System.out.println(); 

    } 

    public void imageUpload(FileUploadEvent event) { 

     imagePath = ""; 

     // Variable to ensure that the query is always enter to same index. 
     int index = -1; 
     String query = ""; 

     FacesContext facesContext = FacesContext.getCurrentInstance(); 
     ExternalContext externalContext = facesContext.getExternalContext(); 
     HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); 

     // File 
     UploadedFile uploadedFile = event.getFile(); 

     // File Name 
     String fileName = uploadedFile.getFileName(); 

     //File Extension 
     String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length()); 

     String path = externalContext.getRealPath("/resources/images") + "/" ; 


     try { 

      //<p:fileUpload id="cityMap" .../> 
      String componentID = event.getComponent().getClientId(); 

      if (componentID.equalsIgnoreCase("cityMap")) { 

       index = 0; 

       /** 
       * UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value 
      */ 
       query = "UPDATE city set citymap=(?) where cityid=" + cityID; 

       boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID); 
       boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile); 

       if (outcome) { 

        addImageNameToList(index, "cityMap_" + cityID + fileExtension); 

        setImage(imagePath1, "cityMap_" + cityID + fileExtension); 
        //imagePath = imagePath + "cityMap" + fileExtension; 

       } 

      } else if (componentID.equalsIgnoreCase("cityImage1")) { 

       index = 1; 
       query = "UPDATE city set cityimage1=(?) where cityid=" + cityID; 

       boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage1_" + cityID); 
       boolean outcome = ConnectionUtil.createFile("cityImage1_" + cityID, fileExtension ,path, uploadedFile); 

       if (outcome) { 

        addImageNameToList(index, "cityImage1_" + cityID + fileExtension); 
        setImage(imagePath1, "cityImage1_" + cityID + fileExtension); 

       } 

      } else if (componentID.equalsIgnoreCase("cityImage2")) { 

       index = 2; 
       query = "UPDATE city set cityimage2=(?) where cityid=" + cityID; 

       boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage2_" + cityID); 
       boolean outcome = ConnectionUtil.createFile("cityImage2_", fileExtension ,path, uploadedFile); 

       if (outcome) { 

        addImageNameToList(index, "cityImage2_" + cityID + fileExtension); 
        setImage(imagePath1, "cityImage2_" + cityID + fileExtension); 

       } 

      } else if (componentID.equalsIgnoreCase("cityImage3")) { 

       index = 3; 
       query = "UPDATE city set cityimage3=(?) where cityid=" + cityID; 

       boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityImage3_" + cityID); 
       boolean outcome = ConnectionUtil.createFile("cityImage3_" + cityID, fileExtension ,path, uploadedFile); 

       if (outcome) { 

        addImageNameToList(index, "cityImage3_" + cityID + fileExtension); 
        setImage(imagePath1, "cityImage3_" + cityID + fileExtension); 

       } 

    } catch (Exception e) { 

     FacesMessage msg = new FacesMessage("Exception happen"); 
     FacesContext.getCurrentInstance().addMessage(null, msg); 

     e.printStackTrace(); 

     // return null; 

    } 

} //end of imageUpload() 

private void setImage(String path, String fileName) { 

    imagePath = path + fileName; 

} 

입니다. 이 문제를 어떻게 방지 할 수 있습니까? 5 개의 이미지 경로 변수를 만든 다음 다른 곳에 저장합니까? 하지만 50 이미지가 있다면? 더 좋은 옵션이 있습니까? 내가 다시이 페이지를 업로드 할 때 다시 올 때 모든 것이 그대로이 페이지에 그대로 남아 있습니까?

답변

0

몇 가지 코드와 이상한 있습니다

  • 당신은 당신의 콩, ViewScoped 또는 SesssionScoped에 대한 단일 범위를 선택해야합니다.
  • 모든 h : graphicImage 구성 요소가 실제로 동일한 값에 바인딩되어야합니까?
  • bean의 imagePath 속성을 볼 수 없습니다.
+0

안녕하세요. 네, 모든 이미지에 대해 동일한 경로를 사용했고 시스템 이벤트를 사용하여이 작업을 수행했습니다. 내 의견에 어떻게 코드를 넣을 수 있을지 모르겠다. 또한 한계는 매우 제한적입니다. 모든 것이 잘 작동합니다. 실제로 내가 파일을 업로드 버튼을 누르면 내 생성자가 호출되지 않기 때문에보기 범위를 사용했습니다. 내 페이지에 5 개의 파일 업로드 버튼이 있고 파일 업로드 버튼을 클릭 할 때마다 생성자 호출을 알게되었습니다. 내가 이미지 이름을 목록에 저장하고 세션 변수에 목록을 저장하기 때문에 세션 범위를 사용했습니다. – Basit

+0

만약 내가보기 범위 만 사용한다면 어떻게 이미지 이름을 세션에 저장할 수 있습니까? 그리고 만약 내가보기 범위를 사용했다면 생성자는 여러 번 호출합니다. 그래서 내가 두 범위를 모두 사용했습니다. 이것이 나쁜 습관이라면 최선의 방법을 알고 싶기 때문에 알려주십시오. 오, 죄송합니다. 실제로 이미지 경로를 반환하기 때문에 실제로 getter 속성을 표시하지 않았습니다. 여기에 내 재산 :) 공용 문자열 getImagePath() { 반환 imagePath; } 고마워요 :) – Basit

+0

관리 빈은 두 개의 범위를 가질 수 없으며, sessionscope는 viewscope보다 오래 지속됩니다.탐색하는 동안 페이지의 상태를 유지하려면 세션 범위에 넣거나 FlashScope (http://www.jroller.com/HazemBlog/entry/understanding_the_jsf_2_0)와 함께 viewscope를 사용해야합니다. 플래시 스코프는 다르게 작동하므로 다른 스코프와 함께 사용할 수 있습니다. –

0

이미지를 @SessionScoped 빈에 저장하거나 이미지를 업로드 한 후 일부 영구 저장 장치에 저장하십시오.

+0

일부 이미지 변수가 아닌 경로에서 이미지를 가져옵니다. 코드를 보면 모든

에서 동일한 경로를 사용했는데 ID를 기준으로 pat을 만들고 그 경로에서 이미지를 가져옵니다. 또한 @SessionScoped 주석을 사용했습니다. 이 주석은 콩이 Session 범위를 가지고 있다는 것을 나타내지 않습니까? 국가가 구원 받습니까? – Basit

0

안녕하세요. 여기에 먼저 내 HTML

<h:form id="cityDetailForm" prependId="false" > 

       <p:growl id="messages" 
         showDetail="true" /> 

       <p:panel id="panel1" 
         style="border-color: #000000;width: 954px;position: absolute;left: 150px;height: 450px;-moz-border-radius: 11px; -webkit-border-radius: 11px; border-radius: 11px; behavior: url(../PIE/PIE.htc)"> 

        <strong Class="MainHeader"> 
         <p:spacer width="10"/> City Detail 
        </strong> 

        <h:panelGrid columns="5" 
           border="" 
           width="20%" 
           style="position: absolute; top: 50px;" 
           columnClasses="asteriskColumns, nameColumns" > 

         <h:outputText value="*" /> 
         <h:outputText value="Map: " /> 
         <p:fileUpload id="cityMap" 
             description="Image" 
             update="city messages" 
             allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
             auto="true" 
             fileUploadListener="#{cityDetail.imageUpload}" > 

         </p:fileUpload> 

         <p:graphicImage id="city" 
             value="#{cityDetail.imagePath}" 
             width="80" 
             height="50" 
             cache="false"> 

          <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" /> 

         </p:graphicImage> 

         <p:commandLink update="city" 
             action="#{cityDetail.removeImage}" 
             style="color: #0d5b7f;text-decoration: underline"> 

          <h:outputText value="remove" /> 

         </p:commandLink> 


         <h:outputText value="*" /> 
         <h:outputText value="Image1: " /> 
         <p:fileUpload id="cityImage1" 
             description="Image" 
             update="Image1 messages" 
             allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
             auto="true" 
             fileUploadListener="#{cityDetail.imageUpload}" > 


         </p:fileUpload> 

         <p:graphicImage id="Image1" 
             value="#{cityDetail.imagePath}" 
             width="80" 
             height="50" 
             cache="false" > 

          <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" /> 

         </p:graphicImage> 

         <p:commandLink update="Image1" 
             action="#{cityDetail.removeImage}" 
             style="color: #0d5b7f;text-decoration: underline"> 

          <h:outputText value="remove" /> 

         </p:commandLink> 

         <h:outputText value="*" /> 
         <h:outputText value="Image2: " /> 
         <p:fileUpload id="cityImage2" 
             description="Image" 
             update="Image2 messages" 
             allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
             auto="true" 
             fileUploadListener="#{cityDetail.imageUpload}" > 

         </p:fileUpload> 

         <p:graphicImage id="Image2" 
             value="#{cityDetail.imagePath}" 
             width="80" 
             height="50" 
             cache="false" > 

          <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" /> 


         </p:graphicImage> 

         <p:commandLink update="Image2" 
             action="#{cityDetail.removeImage}" 
             style="color: #0d5b7f;text-decoration: underline"> 

          <h:outputText value="remove" /> 

         </p:commandLink> 



         <h:outputText value="*" /> 
         <h:outputText value="Image3: " /> 
         <p:fileUpload id="cityImage3" 
             description="Image" 
             update="Image3 messages" 
             allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
             auto="true" 
             fileUploadListener="#{cityDetail.imageUpload}" > 

         </p:fileUpload> 

         <p:graphicImage id="Image3" 
             value="#{cityDetail.imagePath}" 
             width="80" 
             height="50" 
             cache="false" > 

          <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" /> 


         </p:graphicImage> 

         <p:commandLink update="Image3" 
             action="#{cityDetail.removeImage}" 
             style="color: #0d5b7f;text-decoration: underline"> 

          <h:outputText value="remove" /> 

         </p:commandLink> 

         <h:outputText value="*" /> 
         <h:outputText value="Image4: " /> 
         <p:fileUpload id="cityImage4" 
             description="Image" 
             update="Image4 messages" 
             allowTypes="*.jpg;*.png;*.gif;*.jpeg;" 
             auto="true" 
             fileUploadListener="#{cityDetail.imageUpload}" > 

         </p:fileUpload> 

         <p:graphicImage id="Image4" 
             value="#{cityDetail.imagePath}" 
             width="80" 
             height="50" 
             cache="false" > 

          <f:event type="preRenderComponent" listener="#{cityDetail.putImage}" /> 

         </p:graphicImage> 

         <p:commandLink update="Image4" 
             action="#{cityDetail.removeImage}" 
             style="color: #0d5b7f;text-decoration: underline"> 

          <h:outputText value="remove" /> 

         </p:commandLink> 

        </h:panelGrid> 

        <h:commandButton id="preview" 
            value="Preview" 
            action="#{cityDetail.preview}" 
            style="position: absolute; top: 350px;" 
            styleClass="ButtonStyle" /> 

        <h:commandButton id="save" 
            value="Save" 
            actionListener="#{cityDetail.sendImagesToDatabase}" 
            action="#{cityDetail.save}" 
            style="position: absolute; top: 350px; left: 90px;" 
            styleClass="ButtonStyle" /> 

        <h:commandButton id="cancel" 
            value="Cancel" 
            action="#{cityDetail.cancel}" 
            style="position: absolute; top: 350px; left: 165px;" 
            styleClass="ButtonStyle" /> 

       </p:panel> 

      </h:form> 

이며, 지금 여기 내 콩

@ManagedBean 
@ViewScoped 
@SessionScoped 
public class CityDetail { 

private StreamedContent image; 
private ArrayList images; 
private ArrayList imageNames; 
private String imagePath = "/resources/images/Untitled.jpg"; 
private String imagePath1 = "/resources/images" + "/"; 
private boolean remove = false; 
private String once; 

private static int x = 0; 

// Set in the City_Review Page, in session variable 
public int cityID; 

/** Creates a new instance of CityDetail */ 
public CityDetail() { 



    /** 
    * If we come from cityView.xhtml page then this contain value. We are using this because we 
    * want that when user come from cityView.xhtml page then old values should be retain. 
    */ 
    imageNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames"); 
    images = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImages"); 


    if (imageNames == null) { 

     imageNames = new ArrayList(); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 
     imageNames.add(""); 

    } //end of if() 

    if (images == null) { 

     images = new ArrayList(); 
     images.add(""); 
     images.add(""); 
     images.add(""); 
     images.add(""); 
     images.add(""); 

    } 

    // Getting session ID from seession variable that is set in the City_Review Page 
    cityID = Integer.parseInt(ConnectionUtil.session.getAttribute("CityID").toString()); 

    once = ConnectionUtil.session.getAttribute("once").toString(); 

    if (once.equalsIgnoreCase("true")) { 

     //SELECT column_name(s) FROM table_name WHERE column_name operator value 
     String cityMapQuery = "SELECT citymap From city Where cityid='" + cityID + "'"; 
     String cityImage1Query = "SELECT cityimage1 From city Where cityid='" + cityID + "'"; 
     String cityImage2Query = "SELECT cityimage2 From city Where cityid='" + cityID + "'"; 
     String cityImage3Query = "SELECT cityimage3 From city Where cityid='" + cityID + "'"; 
     String cityImage4Query = "SELECT cityimage4 From city Where cityid='" + cityID + "'"; 

     ArrayList cityMapQueryArray = new ArrayList(); 
     cityMapQueryArray.add(cityMapQuery); 

     ArrayList cityImage1QueryArray = new ArrayList(); 
     cityImage1QueryArray.add(cityImage1Query); 

     ArrayList cityImage2QueryArray = new ArrayList(); 
     cityImage2QueryArray.add(cityImage2Query); 

     ArrayList cityImage3QueryArray = new ArrayList(); 
     cityImage3QueryArray.add(cityImage3Query); 

     ArrayList cityImage4QueryArray = new ArrayList(); 
     cityImage4QueryArray.add(cityImage4Query); 

     ArrayList mainArray = new ArrayList(); 

     mainArray.add(cityMapQueryArray); 
     mainArray.add(cityImage1QueryArray); 
     mainArray.add(cityImage2QueryArray); 
     mainArray.add(cityImage3QueryArray); 
     mainArray.add(cityImage4QueryArray); 


    } //end of if 



    System.out.println(); 

} //end of constructor() 

//Getters and setters --------------------- 

public StreamedContent getImage() { 
    return image; 
} 

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

public String getImagePath() { 
    return imagePath; 
} 

public void setImagePath(String imagePath) { 
    this.imagePath = imagePath; 
} 

//public String imageUpload(FileUploadEvent event) { 
public void imageUpload(FileUploadEvent event) { 

    imagePath = ""; 

    // Variable to ensure that the query is always enter to same index. 
    int index = -1; 
    String query = ""; 

    FacesContext facesContext = FacesContext.getCurrentInstance(); 
    ExternalContext externalContext = facesContext.getExternalContext(); 
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); 

    // File 
    UploadedFile uploadedFile = event.getFile(); 

    // File Name 
    String fileName = uploadedFile.getFileName(); 

    //File Extension 
    String fileExtension = fileName.substring(fileName.lastIndexOf('.'), fileName.length()); 

    String path = externalContext.getRealPath("/resources/images") + "/" ; 

    try { 

     //<p:fileUpload id="cityMap" .../> 
     String componentID = event.getComponent().getClientId(); 

     if (componentID.equalsIgnoreCase("cityMap")) { 

      index = 0; 

      /** 
      * UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value 
      */ 
      query = "UPDATE city set citymap=(?) where cityid=" + cityID; 

      boolean reslut = ConnectionUtil.deleteImageIfExist(path, "cityMap_" + cityID); 
      boolean outcome = ConnectionUtil.createFile("cityMap_" + cityID, fileExtension ,path, uploadedFile); 

      if (outcome) { 

       addImageNameToList(index, "cityMap_" + cityID + fileExtension); 
       // setImage(imagePath1, "cityMap_" + cityID + fileExtension, index); 
       // imagePath = imagePath1 + "cityMap_" + cityID + fileExtension; 

      } 

     } else if (componentID.equalsIgnoreCase("cityImage1")) { 

      index = 1; 
      query = "UPDATE city set cityimage1=(?) where cityid=" + cityID; 

      boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage1_" + cityID); 
      boolean outcome = ConnectionUtil.createFile("sityImage1_" + cityID, fileExtension ,path, uploadedFile); 

      if (outcome) { 

       addImageNameToList(index, "sityImage1_" + cityID + fileExtension); 

      } 

     } else if (componentID.equalsIgnoreCase("cityImage2")) { 

      index = 2; 
      query = "UPDATE city set cityimage2=(?) where cityid=" + cityID; 

      boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage2_" + cityID); 
      boolean outcome = ConnectionUtil.createFile("sityImage2_" + cityID, fileExtension ,path, uploadedFile); 

      if (outcome) { 

       addImageNameToList(index, "sityImage2_" + cityID + fileExtension); 

      } 

     } else if (componentID.equalsIgnoreCase("cityImage3")) { 

      index = 3; 
      query = "UPDATE city set cityimage3=(?) where cityid=" + cityID; 

      boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage3_" + cityID); 
      boolean outcome = ConnectionUtil.createFile("sityImage3_" + cityID, fileExtension ,path, uploadedFile); 

      if (outcome) { 

       addImageNameToList(index, "sityImage3_" + cityID + fileExtension); 

      } 

     } else if (componentID.equalsIgnoreCase("cityImage4")) { 

      index = 4; 
      query = "UPDATE city set cityimage4=(?) where cityid=" + cityID; 

      boolean reslut = ConnectionUtil.deleteImageIfExist(path, "sityImage4_" + cityID); 
      boolean outcome = ConnectionUtil.createFile("sityImage4_" + cityID, fileExtension ,path, uploadedFile); 

      if (outcome) { 

       addImageNameToList(index, "sityImage4_" + cityID + fileExtension); 

      } 

     } //end of else if() 

     // Convert file from input stream to bytes 
     byte[] byteArray = event.getFile().getContents(); 

     /** 
     * Add images to list so we can retrieve them when user click on save button 
     */ 
     // boolean add = images.add(new Images(query, byteArray)); 


     //Check for multiple clicks on the same Browse Button 
     // If index has value then replace the value rather then add new value to List 
     images.set(index, new Images(query, byteArray)); 



     //byteArray used to store picture into database 
     InputStream ist = new ByteArrayInputStream(byteArray); 

     /* 
     * StreamedContent Object used to show the picture in jsf pages. We need to convert 
     * again bytearray to InputStream 
     */ 
     image = new DefaultStreamedContent(ist, "image/jpg"); 


     FacesMessage msg = new FacesMessage(fileName + " succesfully uploaded."); 
     FacesContext.getCurrentInstance().addMessage(null, msg); 

     //we dont need to use faces-config to navigate in jsf 2 
     // return null ; 

    } catch (Exception e) { 

     FacesMessage msg = new FacesMessage("Exception happen"); 
     FacesContext.getCurrentInstance().addMessage(null, msg); 

     e.printStackTrace(); 

     // return null; 

    } //end of catch (Exception e) 

} //end of imageUpload() 

/** 
    * This method called when user click on "save" button on page cityDetail.xhtml . 
    * This method is called before save() function is executed. Because action listener 
    * runs first. 
    * @return 
    */ 
public void sendImagesToDatabase(ActionEvent e) { 

    ArrayList mainArray = new ArrayList(); 

    for(int i=0; i<images.size(); i++) { 

     ArrayList innerArray = new ArrayList(); 

     if (images.get(i).equals("")) { 

      continue; 

     } else { 

      Images imageObject =(Images)images.get(i); 

      String query = imageObject.getQuery(); 
      byte[] image = imageObject.getImageBytes(); 

      innerArray.add(query); 
      innerArray.add(image); 

      mainArray.add(innerArray); 

     } 

    } //end of for() 

    int executeDocumentUpdateBatch = ConnectionUtil.executeDocumentUpdateBatch(mainArray); 

    System.out.println(executeDocumentUpdateBatch); 

} //end of sendImagesToDatabase() 

/** 
    * This method is called when user click on "preview" button on page cityDetail.xhtml 
    * @return 
    */ 
public String preview() { 

    ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames); 
    ConnectionUtil.session.setAttribute("cityDetailImages", images); 

    return "cityView?faces-redirect=true"; 

} //end of preview() 

/** 
    * This method called when user click on "save" button on page cityDetail.xhtml . 
    * This method is called after sendImagesToDatabase() function is executed. Because action listener 
    * runs first. 
    * @return 
    */ 
public String save() { 

    ConnectionUtil.session.setAttribute("cityDetailImageNames", imageNames); 
    ConnectionUtil.session.setAttribute("cityDetailImages", images); 

    return "cityDetail?faces-redirect=true"; 
    //return null; 

} //end of save() 

public String cancel() { 

    ConnectionUtil.session.setAttribute("cityDetailImageNames", null); 
    ConnectionUtil.session.setAttribute("cityDetailImages", null); 

    return "City_AddUpdate?faces-redirect=true"; 

} //end of cancel() 

private void addImageNameToList(int index, String fileName) { 

     imageNames.set(index, fileName); 

} //end of addImageNameToList() 

/** 
    * This method is called when user click on remove link on page cityDetail.xhtml beside each image. 
    * We simply set boolean variable "remove" to true so when "update = <p:graphicImage Id />" 
    * in <p:commandLink /> is called then <p:graphicImage /> with the mentioned ID is called and 
    * its putImage() method is called. Then in the method we handle remove image procedure. 
    */ 
public void removeImage() { 

    remove = true; 

} //end of removeImage() 

/** 
    * This method is called for every <p:graphicImage /> because we use "type = preRenderComponent" 
    * on every <p:graphicImage /> . In this method we we set image path and also check whether 
    * user coming from preview page so we can again set images to the same position. 
    * @param event 
    */ 
public void putImage(ComponentSystemEvent event) { 

    boolean test = remove; 

    boolean found = false; 



    x++; 
    int y = x; 

    GraphicImage image1 = (GraphicImage)event.getComponent(); 

    String imageURL = image1.getUrl(); 
    String imageDir = image1.getDir(); 
    String imageValue = image1.getValue().toString(); 
    String imageId = image1.getClientId(); 

    ArrayList imagesNames = (ArrayList)ConnectionUtil.session.getAttribute("cityDetailImageNames"); 

    if (imagesNames == null) { 

     for (int i=0; i<imageNames.size(); i++) { 

      String fileName = imageNames.get(i).toString(); 

      if (fileName.contains(imageId)) { 

       if (remove) { 

        imagePath = ""; 
        imagePath = "/resources/images/Untitled.jpg"; 

        //also remove from list so when on preview page this list called using session 
        // it contains "" for the remove value. Otherwise image deleted from 
        //cityDetail page but shown when preview is clicked 
        imageNames.set(i, ""); 
        remove = false; 
        break; 

       } else { 

        imagePath = ""; 
        imagePath = imagePath1 + fileName; 
        break; 

       } 

      } //end of if 

     } //end of for() 

    } else { //handle when retrun from preview page 

     for(int i=0; i<imagesNames.size(); i++) { 

      String fileName = imagesNames.get(i).toString(); 

      if (fileName.contains(imageId)) { 

       if (remove) { 

        imagePath = ""; 
        imagePath = "/resources/images/Untitled.jpg"; 
        imageNames.set(i, ""); //also remove from list 
        remove = false; 
        break; 

       } else { 

        imagePath = ""; 
        imagePath = imagePath1 + fileName; 
        break; 

       } 

      } else if (fileName.equalsIgnoreCase("")) { 

       imagePath = ""; 
       imagePath = "/resources/images/Untitled.jpg"; 
       break; 

      } 

     } //end of for 

    } 

    System.out.println(); 
    System.out.println(); 
    System.out.println(); 



} //end of putImage 



} //end of class CityDetail 

지금 그때 알려 주시기 바랍니다 잘못하고 대한 unusal 아무것도 할 경우입니까? 이 코드는 잘 작동하지만 정상적으로 작동한다고해서 그것이 완벽하거나 정확하다는 것을 의미하지는 않습니다.

감사합니다.

관련 문제