我正在使用一个 Web 应用程序,其中有一个 Java Applet,可以将 wacom 设备中的图像捕获到 RenderedImage
对象中。小程序本身嵌入到 JSF 2.0 页面中。
我需要将创建的 RenderedImage
从 Applet 传递到 JSF 支持 bean,以便它成为 User
对象的一部分。我的支持 bean 是 View 范围的。
我真的迷失了。我一直在寻找一个关于如何实现这一目标的好例子。我应该使用 JSObject
,还是应该将图像发送到 servlet?
您能否就如何解决这个问题提供一些建议?
最佳答案
您的问题可以分为以下子步骤:
- 从
BufferedImage
创建一个字节数组保存其数据; - 对数据进行正确编码,以便在将数据作为字符串发送到服务器时不会被损坏/修改,例如使用 Apache Commons Base64 codec ;
- 通过 Applet 到 JavaScript 通信将数据保存为隐藏表单字段;
- 通过触发
<h:commandButton>
等方式向服务器发送 POST 请求的onclick
; - 以标准 JSF 方式将编码字符串写入 java bean 属性;
- 对字符串进行解码,得到代表图像的字节数组;
- 从字节数组重新创建图像并将其注入(inject)您的 View 作用域 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;
}
}
关于java - 如何将图像从 Applet 传递到 JSF 支持 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552202/