Spring MVC File Upload Example

 1.Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project

New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.

New Maven project

New Maven project- step 2

Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes", the “Archetype artifact Id” variable to"maven-archetype-webapp" and the “Archetype Version” to "1.0". Click on “OK” to continue.

maven-archetype-webapp

Add Maven archetype

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample"and the project name as "springexample". Set the “Package” variable to "war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

Configure Maven project

Configure Maven project

The Maven project structure is shown below:

New project structure

New project structure

  • It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring-MVC dependencies

Add the dependencies in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc package. The javax.validation and the hibernate-validator packages will be also used here for validation. The commons-io and commons-fileupload packages are used for uploading the file.

pom.xml

02     <modelVersion>4.0.0</modelVersion>
03     <groupId>com.javacodegeeks.snippets.enterprise</groupId>
04     <artifactId>springexample</artifactId>
05     <packaging>war</packaging>
06     <version>0.0.1-SNAPSHOT</version>
07     <name>springexample Maven Webapp</name>
08     <url>http://maven.apache.org</url>
09     <dependencies>
10         <dependency>
11             <groupId>org.springframework</groupId>
12             <artifactId>spring-webmvc</artifactId>
13             <version>${spring.version}</version>
14         </dependency>
15  
16         <dependency>
17             <groupId>javax.servlet</groupId>
18             <artifactId>servlet-api</artifactId>
19             <version>2.5</version>
20         </dependency>
21         <dependency>
22             <groupId>javax.validation</groupId>
23             <artifactId>validation-api</artifactId>
24             <version>1.1.0.Final</version>
25         </dependency>
26         <dependency>
27             <groupId>org.hibernate</groupId>
28             <artifactId>hibernate-validator</artifactId>
29             <version>5.1.0.Final</version>
30         </dependency>
31         <dependency>
32             <groupId>commons-io</groupId>
33             <artifactId>commons-io</artifactId>
34             <version>2.4</version>
35         </dependency>
36         <dependency>
37             <groupId>commons-fileupload</groupId>
38             <artifactId>commons-fileupload</artifactId>
39             <version>1.3.1</version>
40         </dependency>
41         <dependency>
42             <groupId>javax.servlet</groupId>
43             <artifactId>jstl</artifactId>
44             <version>1.2</version>
45         </dependency>
46     </dependencies>
47     <build>
48         <finalName>springexample</finalName>
49         <plugins>
50             <plugin>
51                 <groupId>org.apache.maven.plugins</groupId>
52                 <artifactId>maven-compiler-plugin</artifactId>
53                 <version>3.1</version>
54                 <configuration>
55                     <source>1.7</source>
56                     <target>1.7</target>
57                     <fork>true</fork>
58                     <executable>${JAVA_HOME}/bin/javac</executable>
59                     <encoding>UTF-8</encoding>
60                 </configuration>
61             </plugin>
62             <plugin>
63                 <groupId>org.apache.maven.plugins</groupId>
64                 <artifactId>maven-assembly-plugin</artifactId>
65                 <version>2.3</version>
66             </plugin>
67         </plugins>
68     </build>
69  
70     <properties>
71         <spring.version>3.2.9.RELEASE</spring.version>
72     </properties>
73 </project>   

3. Create the model

File.java is a simple Java class, with a property named field, This field is aorg.springframework.web.multipart.MultipartFile, which is a representation of an uploaded file received in a multipart request. It has getters and setters, so that it is accessible from the view.

File.java

01 package com.javacodegeeks.snippets.enterprise.fileupload.model;
02  
03 import org.springframework.web.multipart.MultipartFile;
04  
05 public class File {
06           
07         MultipartFile file;
08          
09         public MultipartFile getFile() {
10             return file;
11         }
12  
13         public void setFile(MultipartFile file) {
14             this.file = file;
15         }      
16 }

4. Create a Validator

The validator created here checks if there is a file uploaded. It specifically checks the size of the file and if it is equal tozero, then a validation message is rendered in the view.

In order to create a validator class, we are making use of the API provided by Spring MVC. FileValidator.java below implements the org.springframework.validation.Validator, and overrides the two methods it provides.

The boolean supports(Class<?> paramClass) method is used to check if the validator can validate instances of theparamClass.

In the validate(Object obj, Errors errors) method, an instance of the class is provided, and an Errors object. Theorg.springframework.validation.ValidationUtils is used here, since it offers validation API methods to check the fields of the object. So in this method we can check if the the file size is equal to zero. All error messages are passed in the errorobject. A properties file with error messages is used here to pass various validation messages to the errors object as shown below:

FileValidator.java

01 package com.javacodegeeks.snippets.enterprise.fileupload.validator;
02  
03 import org.springframework.validation.Errors;
04 import org.springframework.validation.Validator;
05  
06 import com.javacodegeeks.snippets.enterprise.fileupload.model.File;
07  
08 public class FileValidator implements Validator {
09     public boolean supports(Class<?> paramClass) {
10         return File.class.equals(paramClass);
11     }
12  
13     public void validate(Object obj, Errors errors) {
14         File file = (File) obj;
15           if (file.getFile().getSize() == 0) {
16            errors.rejectValue("file""valid.file");
17           }
18     }
19 }

The validation.properties file below is the file that contains the error message.

validation.properties

1 valid.file= Please select a file!

5. Create the Controller

The Controller is where the DispatcherServlet will delegate requests. The @Controller annotation indicates that the class serves the role of a Controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

org.springframework.validation.Validator is injected here, via the @Autowired annotation, also making use of the@Qualifier annotation to specify that the FileValidator.java implementation of theorg.springframework.validation.Validator class is injected.

The @InitBinder annotation in initBinder(WebDataBinder binder) method allows us to configure web data binding directly within the controller. With @InitBinder we can initialize the WebDataBinder, that is used for data binding from web request parameters to JavaBean objects. Here, the WebDataBinder is where the validator is set.

The Controller consists of two basic methods, a GET method, which is String initForm(Model model) and a POST method, which is String submitForm(Model model, @Validated File file, BindingResult result). The first method creates and returns to the "file" view a new instance of the File.java class. The second method also gets the Model, and the Fileobject created, which now has the uploaded file in its file param. File is annotated with the @Validated annotation, which allows the file object to be validated with the validator. BindingResult is where all validation errors are automatically passed, so it can be used to decide the next navigation step. If there are no errors, the validation is successful, so the method returns the String representation of the successFile.jsp page, and the file object is passed at the Model. Otherwise, the returned String is the String representation of the file.jsp page, which also has the error messages, as will be shown below.

FileController.java

01 package com.javacodegeeks.snippets.enterprise.fileupload;
02  
03 import org.springframework.beans.factory.annotation.Autowired;
04 import org.springframework.stereotype.Controller;
05 import org.springframework.ui.Model;
06 import org.springframework.validation.BindingResu<
07 import org.springframework.validation.annotation.Validated;
08 import org.springframework.web.bind.WebDataBinder;
09 import org.springframework.web.bind.annotation.InitBinder;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12 import org.springframework.web.multipart.MultipartFile;
13  
14 import com.javacodegeeks.snippets.enterprise.fileupload.model.File;
15 import com.javacodegeeks.snippets.enterprise.fileupload.validator.FileValidator;
16  
17 @Controller
18 @RequestMapping("/file.htm")
19 public class FileController {
20  
21     @Autowired
22     FileValidator validator;
23  
24     @InitBinder
25     private void initBinder(WebDataBinder binder) {
26         binder.setValidator(validator);
27     }
28  
29     @RequestMapping(method = RequestMethod.GET)
30     public String getForm(Model model) {
31         File fileModel = new File();
32         model.addAttribute("file", fileModel);
33         return "file";
34     }
35  
36     @RequestMapping(method = RequestMethod.POST)
37     public String fileUploaded(Model model, @Validated File file,
38             BindingResult result) {
39  
40         String returnVal = "successFile";
41         if (result.hasErrors()) {
42             returnVal = "file";
43         else {           
44             MultipartFile multipartFile = file.getFile();
45         }
46         return returnVal;
47     }
48 }

6. Create the view to upload the file

The view below is a simple example of how to create a form where a file can be uploaded. It is a simple html view consisting of the head and body html tags.

In order to create a form in Spring MVC, we make use of the form:form tag. Its method property is set to POST, and thecommandName property is set to the name of the backing bean that is binded to the Model, which is the File.java class.

Inside the form:form tag, we are making use of the enctype="multipart/form-data" attribute, which lets the browser know how to encode the form as multipart request.

The input tag with type property set to file is used to place the uploaded file. The form:errors tag defines where the error message of the specified field will be displayed in the view. Finally, the input tag, with type property set to uploadis used for the upload button.

file.jsp

01 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
02 <html>
03   
04 <body>
05  
06 <h2>Spring MVC - Uploading a file.. </h2>
07     <form:form method="POST" commandName="file"  enctype="multipart/form-data">
08   
09         Upload your file please:
10         <input type="file" name="file" />
11         <input type="submit" value="upload" />
12         <form:errors path="file" cssStyle="color: #ff0000;" />
13     </form:form>
14   
15 </body>
16 </html>

Below is the page that will be rendered when the file upload succeeds:

successFile.jsp

1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form">
2 <html>
3 <body>
4 <h2>Spring MVC - Uploading a file.. </h2>
5 Your file is successfully uploaded.
6 </body>
7 </html>

7. Configure the application

The files that we must configure in the application are the web.xml file and the mvc-dispatcher-servlet.xml file.

The web.xml file is the file that defines everything about the application that a server needs to know. It is placed in the/WEB-INF/ directory of the application. The <servlet> element declares the DispatcherServlet. When theDispatcherServlet is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in /WEB-INF/ directory. So, we have created the mvc-dispatcher-servlet.xml file, that will be explained below. The <servlet-mapping> element of web.xml file specifies what URLs will be handled by theDispatcherServlet.

web.xml

01 <?xml version="1.0" encoding="UTF-8"?>
02 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name>
03   
04     <servlet>
05         <servlet-name>mvc-dispatcher</servlet-name>
06         <servlet-class>
07             org.springframework.web.servlet.DispatcherServlet
08         </servlet-class>
09         <load-on-startup>1</load-on-startup>
10     </servlet>
11   
12     <servlet-mapping>
13         <servlet-name>mvc-dispatcher</servlet-name>
14         <url-pattern>/</url-pattern>
15     </servlet-mapping>
16 </web-app>

 
The mvc-dispatcher-servlet.xml file is also placed in WebContent/WEB-INF directory. Theorg.springframework.web.servlet.view.InternalResourceViewResolver bean is used as internal resource views resolver, meaning that it will find the jsp and html files in the WebContent/WEB-INF/ folder. We can also set properties such asprefix or suffix to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers are placed and defined.

The <context:component-scan> tag is used, so that the Spring container will search for all annotated classes under thecom.javacodegeeks.snippets.enterprise package. The <mvc:annotation-driven> tag is used, so that the container searches for annotated classes, to resolve MVC. The FileValidator.java class is also defined here as a bean, with an id.

The org.springframework.web.multipart.commons.CommonsMultipartResolver is also defined here as a bean. This class is needed beacause it is the resolver activated by Spring DispatcherServlet to hand over the file upload request.

Finally, the ResourceBundleMessageSource is used, to provide access to resource bundles using specified basenames. Itsbasename property is set to validation, thus pointing to the properties file that holds the validation messages.

mvc-dispatcher-servlet.xml

02  
03     <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />
04     <mvc:annotation-driven />
05  
06     <bean id="fileValidator"
07         class="com.javacodegeeks.snippets.enterprise.fileupload.validator.FileValidator" />
08  
09     <bean id="multipartResolver"
10         class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
11  
12     <bean id="messageSource"
13         class="org.springframework.context.support.ResourceBundleMessageSource">
14         <property name="basename" value="validation" />
15     </bean>
16  
17     <bean
18         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <property name="prefix">
20             <value>/WEB-INF/</value>
21         </property>
22         <property name="suffix">
23             <value>.jsp</value>
24         </property>
25     </bean>
26  
27 </beans

8. Run the application

Now, let’s run the application. We first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package. The .war file produced must be placed in webapps folder of tomcat. Then, we can start the server.

Hit on:

http://localhost:8080/springexample/file.htm

Then press on the upload button, before having chosen on a file.

upload validation error

upload validation error

As you can see, the validator message is displayed, since no file has been uploaded yet.
Now browse on your computer and choose a file to upload:

upload success

upload success

As a result the successFile.jsp view is rendered.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值