簡體   English   中英

如何將圖像從Applet傳遞到JSF支持bean

[英]How to pass image from Applet to JSF backing bean

我正在使用一個Web應用程序,其中有一個Java Applet,它將圖像從wacom設備捕獲到RenderedImage對象中。 小程序本身嵌入到JSF 2.0頁面中。

我需要將已創建的RenderedImage從Applet傳遞到JSF支持bean,以便它將成為User對象的一部分。 我的支持bean是視圖范圍。

我真的迷失了。 我一直在尋找有關如何實現此目標的好例子。 我應該使用JSObject ,還是應該將圖像發送到servlet?

您可以提供一些有關如何解決此問題的建議嗎?

您的問題可以分為以下幾個子步驟:

  1. 從保存其數據的BufferedImage創建一個字節數組;
  2. 正確編碼數據,以便在將數據作為字符串發送到服務器時不會被損壞/修改,例如使用Apache Commons Base64編解碼器 ;
  3. 通過Applet到JavaScript的通信將數據另存為隱藏表單字段;
  4. 通過觸發<h:commandButton>onclick將POST請求發送到服務器;
  5. 以標准JSF方式將編碼字符串寫入java bean屬性;
  6. 解碼字符串以獲取表示圖像的字節數組;
  7. 從字節數組重新創建圖像並將其注入視圖范圍的bean中。

也就是說,讓我們繼續實施該議程。

在小程序中,您將有一種方法可以執行第(1)-(4)點。 獲取圖像后,以通常的方式調用它:

Java Applet方法:

public void processImage() throws IOException, JSException {
    BufferedImage image = createBufferedImage();//the way you get the image
    /* point 1 */
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ImageIO.write(image, "png", bs);
    bs.flush();
    byte[] imageByteArray = bs.toByteArray();
    bs.close();
    /* point 1 */
    String imageAsString = Base64.encodeBase64String(imageByteArray);//point 2
    /* points 3-4 */
    JSObject window = JSObject.getWindow(this);
    window.call("writeImageValue", new Object[] {imageAsString});
    /* points 3-4 */
}

JSF頁面(表單和JavaScript):

<script>
    function writeImageValue(imageValue) {
        document.getElementById('image').value = imageValue;//point 3
        document.getElementById('image-form:submit').click();//point 4
    }
</script>
<h:form id="image-form">
    <input type="hidden" id="image" name="image" />
    <h:commandButton id="submit" action="#{imageSubmitBean.submitImage}" style="display:none" />
</h:form>

JSF托管bean:

@ManagedBean
@RequestScoped
public class ImageSubmitBean {

    @ManagedProperty("#{param.image}")//point 5
    private String imageAsString;//getter+setter
    @ManagedProperty("#{userBean}")//your view scoped bean
    private UserBean userBean;//getter+setter

    public String submitImage() throws IOException {
        byte[] imageByteArray = Base64.decodeBase64(imageAsString);//point 6
        /* point 7 */
        InputStream is = new ByteArrayInputStream(imageByteArray);
        BufferedImage image = ImageIO.read(is);
        is.close();
        userBean.setUserImage(image);//update your view scoped bean
        /* point 7 */
        return null;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM