Showing posts with label actionSupport. Show all posts
Showing posts with label actionSupport. Show all posts

Monday, April 21, 2008

Struts2, uploading a null file and disappearing ActionMessages

There are two small errors I found in my Struts2 app today. Two little sneaky bastards, caused by my inattention, and perhaps insufficient documentation of Struts2. I'd like to post them both, in case it saves some other newbie's day.

The first one concerns the use of the FileUploadInterceptor. It's a really handy class that manages uploading a file from your webapp's form. It's a part of the defaultStack, so all you need to enable the file upload is one s:file tag on your jsp, and a bunch of getters/setters in your Action class, which will allow you to access the uploaded file, already residing on the server. It's all described in details on RoseIndia.

However, what I haven't found in any of the example code snippets, is checking whether the user has chosen a file at all. In the case of my application, uploading a company's logo is not mandatory - so I needed a test before loading the image, checking whether there's any file being uploaded. So what did I do? Let's see: the FileUploadInterceptor fills in three properties of my action:

Well, if the File pic references the actual file, I simply checked whether it was null: ...which didn't prove to be a good idea. pic just kept on containing a reference to a nonexistent temp file. At first I thought the params interceptor somehow "forgot" to set it to null, if a file had been transferred previously. However, this was not the case. Every time the filename was different, but it was there. What's the solution, then?

It seems that the other two properties aren't there without purpose. Apparently, FileUploadInterceptor works this way: every time it runs, it generates a file name and creates a File object for it, no matter if a file is actually being uploaded. That's a normal behavior. What I should have done is checking the String picFileName property, which is empty if there's nothing being sent, like this: That's it, worked like a charm. Still, I find it a little misleading and think the javadocs of FileUploadInterceptor lack a suitable warning.

The other mistake of mine was while setting the ActionMessages of my action which extends the Struts2's built-in ActionSupport. There it is, down in black and white:

getActionMessages public Collection getActionMessages() Description copied from interface: ValidationAware Get the Collection of Action-level messages for this action. Messages should not be added directly here, as implementations are free to return a new Collection or an Unmodifiable Collection.
...and so it does. Trying to do: resulted in my message "disappearing" in the always empty collection. Man, that felt creepy! ;) It's a pity I haven't noticed this method before: but there's no way I could blame the missing documentation this time - just me and my blondishness :)