There are lots of possible signature while defining Spring's Controller method. I'm confused which one should i use and in which circumstances. For example, I have below scenario. I have to upload a file to server i have written a form for that Below is HTML
<form action="uploadimage?id=${pencil.id}" method="post">
<table border="0">
<tr>
<td style="color:maroon;font-weight:bold;">Change/Upload Image</td>
<td><input type="file" name="image" /></td>
<td><input type="submit" value="upload" /></td>
<td><input type="hidden" name="pencilid" value="${pencil.id}" /></td>
</tr>
</table>
</form>
For this I'm writing controller method. While using @ModelAttribute it throws exception saying can't instantiate bean MaltipartFile as its an Interface and while using @RequestParam it returns 400 error code
using @requestParam
@RequestMapping(value="/uploadimage",method=RequestMethod.POST)
public ModelAndView uploadImage(@RequestParam ("pencilid") String id,@RequestParam("file") MultipartFile file)
{
System.out.println("In Controller");
Pencil pencil=null;
PencilService pencilService=ServiceFactory.getPencilService();
pencil=pencilService.getPencil(Integer.parseInt(id));
ModelAndView model= new ModelAndView("pencilview","pencil",pencil);
model.addObject("id",id);
//MultipartFile file=(MultipartFile)param.get("image");
System.out.println(file.getName());
return model;
}
Using @ModelAttribute
@RequestMapping(value="/uploadimage",method=RequestMethod.POST)
public ModelAndView uploadImage(@ModelAttribute ("pencilid") String id,@ModelAttribute("file") MultipartFile file)
{
System.out.println("In Controller");
Pencil pencil=null;
PencilService pencilService=ServiceFactory.getPencilService();
pencil=pencilService.getPencil(Integer.parseInt(id));
ModelAndView model= new ModelAndView("pencilview","pencil",pencil);
model.addObject("id",id);
//MultipartFile file=(MultipartFile)param.get("image");
System.out.println(file.getName());
return model;
}
Kindly let me know where i'm mistaking in my Sping-servlet.xml i have defined multipartResolver as
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
Let me know if anything else is required.