Reputation: 6689
I am trying to learn Spring framework by building simple website, now I have a problem.
I would want to make something like this: user chooses which file to upload and chooses from a list what type of file it is. For now I have something like this:
<form:form modelAttribute="uploadItem" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form_elem">
<label for="file">File</label>
<input type="file" name="fileData"/>
</div>
<div class="form_elem">
<label for="file_type">File type</label>
<form:select path="fileType">
<form:options items="${fileTypes}" />
</form:select>
</div>
<input type="submit"/>
</fieldset>
now in my controller I have
@RequestMapping(value = "/addWordFile", method = RequestMethod.GET)
public String showFileAdder(Model model) {
model.addAttribute(new UploadItem());
model.addAttribute("fileTypes", Arrays.asList("first type", "second type"));
return "questionFileAdd";
}
@RequestMapping(value = "/addWordFile", method = RequestMethod.POST)
public String processUploadedFile(UploadItem uploadItem, Model model)
throws Exception {
String type=uploadItem.getFileType();
return showFileAdder(model);
}
here is the problem, when user chooses type of the file, I get only a String and I would need to manually create an object, like SimpleFileFileReader using class for name or just using big switch-case statement for every type of file I support.
Is it possible to show String in html form, but when it is processed I would get an object of some class?
Upvotes: 0
Views: 124
Reputation: 691685
This is rather an OO question than a Spring question. What you want is a factory of SimpleFileReader. Simply using a Map<String, SimpleFileReader>
could be your solution:
keySet()
of the map contains all the file typesmap.get(fileType)
to get the SimpleFileReader associated to this typeYou could also use en enum:
public enum FileType {
TYPE_1 {
public SimpleFileReader getFileReader() {
return new Type1SimpleFileReader();
}
},
TYPE_2 {
public SimpleFileReader getFileReader() {
return new Type2SimpleFileReader();
}
};
public abstract SimpleFileReader getFileReader();
}
The FileType.values()
gives you the array of file types. Spring can automatically map an input field to an enum, and getting the associated file reader is as simple as
SimpleFileReader reader = fileType.getFileReader();
Upvotes: 1