Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking.I'm 23, born in Romania, student at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff. I know that I look and act differently from most developers, but this is why you will love to work with me!

Sunday, April 11, 2010

PrimeFaces updating JSF components


Well, a few days ago I tried to accomplish the following task using JSF and PrimeFaces (an amazing set of JSF components): I tried to upload an avatar on my site, and after the avatar is successfully uploaded, to re-render it in page without reloading the page (AJAX refresh style). For this, I have used only PrimeFaces components - I used the <p:graphicImage> to display the avatar, and <p:fileUpload> to upload the avatar picture (a small .jpg). Now, the particularity of this upload is that the avatar picture is always overwriting the existing one, therefore the URL to this picture is always the same (the picture is saved in a public folder (outside WEB-INF), and it is loaded through a link, not dynamically as a stream), like this:
<p:graphicImage id="avatarImageId" url="#{uploadBean.avatarUrl}" width="50" height="50"/>
And, the upload component look like this:
<h:form enctype="multipart/form-data" prependId="false">
<p:fileUpload id="uploadAvatarId" fileUploadListener="#{uploadBean.handleAvatarUpload}"
update="avatarImageId,uploadMessages" sizeLimit="102400" multiple="false"
label="choose" auto="false" allowTypes="*.jpg;" description="Images"/>
</h:form>
As you probaly know, <p:fileUpload> component provides PPR integration "FileUpload is powered by PrimeFacs Partial Page Rendering so after a file is uploaded you can update any JSF component." - http://www.primefaces.org:8080/prime-showcase/ui/fileUploadUpdate.jsf, and this is exacly what the update attribute should do.
Well, the problem is that the avatar is always uploaded correctly (by a request scoped managed bean), but is not correctly displayed/updated. Per example, if the picture is named wqWwqWwq.jpg you can see in figure below how the displayed picture and the uploaded one are not the same:

It seems that this is happening because the picture URL is always the same, therefore we solved this problem by adding a random parameter in the request, like this:
...
Random random = new Random();
String randomString = String.valueOf(random.nextInt(100000));
avatarUrl = "../resources/scripts/web/avatars/" + localAvatar + ";" + randomString;
...

Notice that localAvatar represents the picture name!
Now, the Firebug harvest the next URL:

Done! Now, the problem is solved, and AJAX works fine!

No comments: