我正在使用一个web应用程序,其中有一个Java Applet,它可以将wacom设备中的图像捕获到RenderedImage
对象中。小程序本身被嵌入到JSF 2.0页面中。
我需要将创建的RenderedImage
从Applet传递给JSF支持bean,以便它成为User
对象的一部分。我的backingbean是视图范围的。
我真的很失落。我一直在寻找一个如何实现这一目标的好例子。我应该使用JSObject
,还是应该将图像发送到servlet?
你能就如何解决这个问题提供一些建议吗?
您的问题可以分为以下几个子步骤:
- 从您的
BufferedImage
创建一个字节数组,该数组保存其数据 - 对数据进行正确编码,使其在作为字符串发送到服务器时不会被损坏/修改,例如使用Apache Commons Base64编解码器
- 通过Applet到JavaScript的通信将数据保存为隐藏的表单字段
- 向服务器发送POST请求,例如触发
<h:commandButton>
的onclick
- 以标准JSF方式将编码字符串写入javabean属性
- 对字符串进行解码,得到表示图像的字节数组
- 从字节数组中重新创建图像,并将其注入到视图范围的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;
}
}