0

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?

1 Answer 1

1

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:

  • the keySet() of the map contains all the file types
  • once you get the file type from the GUI, use map.get(fileType) to get the SimpleFileReader associated to this type

You 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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, didn't figure out the simplest solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.