I currently have a Spring MVC controller that takes a MultipartFile
@RequestMapping(method = RequestMethod.POST)
public String doUpload(@RequestParam("file") final MultipartFile file) {
/* ... */
}
The file contains csv data which will be used, one per row, to create a list of domain objects. This is working.
I have written a converter for the line data:
class MyObjectConverter implements org.springframework...Converter<String[], MyObject> {
/* ... */
}
And a Validator for the file
class UploadFileValidator implements org.springframework.validation.Validator {
/* ... */
}
And I have a form to do the uploading:
<form method="post"
action="<@spring.url '/upload'/>"
enctype="multipart/form-data">
<input id="upload" type="file" name="file"/>
<input type="submit" id="uploadButton"/>
</form
But what I really want to do is tie it all together so that my controller can have a method something like
@RequestMapping(method = RequestMethod.POST)
public String doUpload(
@Valid final List<MyObject> objList,
final BindingResult result) { ...}
I know that the Spring MVC framework supports converters and validators, but I am failing to understand how to get them to work together.
First I wrapped the MultipartFile in a form backing object:
Which I then bound to my form:
In the controller I assign a validator:
And this is the validator:
The validator uses a Converter for the line-item conversion to MyObj.
The doPost method now looks like this:
The UploadConverter is much the same as the UploadValidator:
The only problem is that the validation and conversion processes are much the same thing. Luckily the upload files will not be very large so the duplication of effort is not a big problem.