Wednesday, April 27, 2011

Upload Files with Spring MVC

Have you ever tried to upload a file as part of a form to be submited?
In my case I have a form to add or update products, and each product must have an image (JPG file), besides the regular information related to each product: Name, Description, etc.
Then, we need a form with some inputs and a method on one of my controllers to handle this request and we're set.

This topic is really simple to cover, despite of the fact is poorly covered by the official documentation.
Steps
Add entries on your POM
Add a MultipartResolver in your Web Application Context
On your form don't forget to include enctype attribute and make it POST

Add your input type file as regular HTML


In your controller add a method to handle with all params
I'm using FileUtils to save the uploaded file :D
Look carefully to this parameter @RequestParam("productImage") matches to

And you're all set! Easy, Isn't it?

Friday, April 15, 2011

Static Binding vs Dynamic Binding

Today someone asked me if knew what was the difference between Static and Dynamic binding. I was in shock, because I didn't have any idea, I heard while on school (loooooooong time ago) something like that while my OOD teacher was explaining Overriding and Overloading (I always have problems trying to tell apart one from the other one), but this is my definition:
Overriding - always happens between classes in a hierarchy chain.
For example: when you extend from a Class and "override" an existing method to add a different behavior on the child class.

Overloading - can occur within a single class, and does not need to involve a class hierarchy.
For example: you can have on the same class multiple methods with same name and different params and even different return types.

Following the same order of ideas...
Static Binding: Static / Early binding is compile time binding. It means at compile time jvm decides which class member or method is preferred to call.
Dynamic binding: Late binding is run time binding. At run time jvm decides which method to call, depending on object type.
Following my definitions:
Static Binding
a.num will be 10 and 
a1.num will be 10 

Dynamic binding
a.getNum() will return 10 
a1.getNum() will return 20 

Wooow! If you can't controll it don't smoke it dude!!!. Personally, this is good as General Culture Knowledge, but professionally, I think is better to have a good understanding of Overloading and Overriding.
Maybe , I'm too soft, but this is my humble perspective.

Simple reference: Quick ref on this matter