First, although there are quite a few Spring MVC "hello world" tutorials, I couldn't find one that accommodated all of my requirements, so I created the springmvcshell project. It's based on mkyong's excellent Spring 3 MVC Hello World Example, which I modified to:
- Use the Maven standard directory structure
- Work with the Eclipse IDE
- Work with Tomcat
- Use Spring 4 rather than an earlier version
- Use Java 1.7 rather than an earlier version
- Uses a single form to read and write fields from two separate classes
- Includes a file upload control using Spring's MultipartFile interface
First of all, the Maven pom.xml files for the springmvcshell and springmvcgoodness projects are of critical importance. Both pom.xml's include the dependencies for Spring 4.0.0, as well as a reference to the com.springsource.repository.maven.snapshot repository that's required for Maven to find these dependencies. The springmvcgoodness pom.xml also adds dependencies for the Java Server Pages Standard Tag Library (JSTL), the Java Persistence API, and Apache Commons FileUpload.
Next, the project settings are critical to making these projects work with Eclipse and Tomcat. If you clone my springmvcshell and springmvcgoodness repos, you'll automatically have the correct settings, which are stored in the .classpath and .project files. However, it's worth understanding some of the details.
- I converted these projects to faceted form (right-click the project and select Configure | Convert to Faceted Form) and added the Dynamic Web Module facet version 3.0. This makes the projects usable as servlets.
- The Java Build Path is key to avoiding compile-time errors due to missing dependencies. I had to add some libraries to the build path (right-click the project and select Build Path | Configure Build Path, then click the Add Library button). I had to add the EAR Libraries. To eliminate some compiler warnings, I also removed the old version 1.5 JRE System Library and replaced it with the JRE System Library [jre7].
- The Deployment Assembly settings are key to successful deploying on Tomcat and are accessed by right-clicking the project, selecting Properties, and then clicking Deployment Assembly. It's critical that the Maven Dependencies be added here if not already present.
- The approach I took to including fields from two models in one form was to create a wrapper class containing an instance of each model class.
- Once you have such a wrapper class, this view shows how to set the commandName and path attributes to refer to fields of the two model classes.
- Keys to making the file upload work include:
- Adding an HTML input tag with type="file" in the view.
- Adding a CommonsMultipartResolver bean to the servlet configuration XML file.
- Including a parameter like @RequestParam("myfile") MultipartFile myFile in the controller method.