Simple examples of spring MVC upload files and considerations

Source: Internet
Author: User

1. Create a MAVEN project

in Pom.xml, the dependent jar package is introduced, and the POM.XM code is as follows:

<project xmlns= "http://maven.apache.org/POM/4.0.0"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "  xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http:// Maven.apache.org/maven-v4_0_0.xsd ">  <modelVersion>4.0.0</modelVersion>   <groupId>com.kedacom.myupload</groupId>  <artifactId>uploaddemo</artifactId>   <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>   <name>uploaddemo maven webapp</name>  <url>http:// maven.apache.org</url>  <dependencies>    <dependency>       <groupId>junit</groupId>      < Artifactid>junit</artifactid>      <version>3.8.1</version>       <scope>test</scope>    </dependency>        <!--   Compile JSP into servlet, if not, JSP will error  -->    <dependency>       <groupId>javax.servlet</groupId>      <artifactId> servlet-api</artifactid>      <version>2.5</version>       <scope>provided</scope>    </dependency>         <!--jar packages used in SPRING&NBSP;MVC library  -->     <dependency>      <groupId>org.springframework</groupId>       <artifactId>spring-web</artifactId>       <version>${springVersion}</version>    </dependency>     <dependency>      <groupid>org.springframework</groupid>       <artifactId>spring-webmvc</artifactId>       <version>${springVersion}</version>    </dependency>         <!-- fileUpload  Parse the jar-->    < used to upload the file dependency>      <groupid>commons-fileupload</groupid>       <artifactId>commons-fileupload</artifactId>       <version>1.2.1</version>    </dependency>     <dependency>      <groupId>org.apache.commons</groupId>       <artifactId>commons-io</artifactId>       <version>1.3.2</version>    </dependency>  </dependencies>   <build>    <finalName>uploaddemo</finalName>  </build>   <properties>     <springversion>3.2.5.release</ Springversion> </properties></project>

2. Modify the configuration file Web. XML and Springmvc-servlet.xml

we know that a Web project starts with XML, and our XML is configured as follows, mainly referencing the Dispatcherservlet in the next spring MVC

The code is as follows:

<web-app xmlns= "Http://java.sun.com/xml/ns/javaee"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/ Javaee/web-app_3_0.xsd "version=" 3.0 ">    <display-name>archetype created  Web Application</display-name>      <servlet>         <servlet-name>springmvc</servlet-name>         <servlet-class>org.springframework.web.servlet.dispatcherservlet</ servlet-class>    </servlet>    <servlet-mapping>         <servlet-name>springmvc</servlet-name>         <url-pattern>/</url-pattern>    </ Servlet-mapping></web-app>

We know Dispatcherservle

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:mvc="/HTTP/ Www.springframework.org/schema/mvc "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:aop=" Http://www.springframework.org/schema/aop " xmlns:tx=" Http://www.springframework.org/schema/tx "xsi: Schemalocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema /mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org /schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http:// Www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http ://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/SPRING-TX-3.0.XSD&NBSP; " ><!--Scan controller package come in, later request to go here to find the corresponding path  --><context:component-scan base-package= " Com.kedacom.upload.controller "></context:component-scan>   <!--  View parser,/ Web-inf/jsp/+viewname+.jsp -->   <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">         <property name= "prefix"  value= "/web-inf/jsp/" ></property>         <property name= "suffix"  value= ". JSP" ></property>    </bean>      <!--  Support for uploading files  -->    <bean id= "Multipartresolver"  class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "/>             <!--  must have this annotation-driven, or not get static resources, Also note that the value of mapping must not be the same as the beginning of the project name, otherwise there will be a lot of problems  Much to pass through the controler will be a problem-->    <mvc:annotation-driven/>    <!--   Mapping static resources  -->    <!--after the IMG reference picture path to this static mapping   -->     <mvc:resources location= "/lupload/"  mapping= "/lupload/**"  />  </beans >

3. The code results are as follows:

4. The front page code is as follows:

index.jsp

 

Result.jsp will upload the picture to the request, show it, the code is as follows:

result.jsp

<%@ page pageencoding= "Utf-8"%><! DOCTYPE html>

5. The controller processes the uploaded file and saves it and will display the URL to the new page, the code is as follows:

Uploadcontroller.java

package com.kedacom.upload.controller;import java.io.file;import  javax.servlet.http.httpservletrequest;import org.springframework.stereotype.controller;import  Org.springframework.ui.modelmap;import org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.RequestMethod;import  org.springframework.web.bind.annotation.requestparam;import  Org.springframework.web.multipart.MultipartFile, @Controllerpublic  class uploadcontroller {     //Note: This path should not be written as "/upload", otherwise there will be an error of no intention.      @RequestMapping (value =  "/saveuploads", method =  Requestmethod.post)     public string upload (    @ Requestparam (value =  "file",  required = false)  MultipartFile file,     httpservletrequest request, modelmap model) &NBSP;{&NBSP;&NBSP;&NBSP;&NBsp;    system.out.println ("Start");         // Create the path to the file you want to save         string path = request.getsession (). Getservletcontext (). Getrealpath ("Lupload");         //get the file name          string filename = file.getoriginalfilename ();         system.out.println (PATH);         file targetfile = new file (Path, filename);         if  (!targetfile.exists ())  {             targetfile.mkdirs ();        }         //  Save         try {        &nbsP;    file.transferto (targetfile);        }  catch  (exception e)  {             E.printstacktrace ();        }         //the path of the file to the client so that it can request the picture         model.addattribute ("FileUrl ",  request.getcontextpath ()  + "/lupload/"+ filename);         return  "result";     }}

After uploading successfully, we can view the location of our files on our hard drive as follows:

The picture exists inside the lupload.

The static resource mapping in the previous springmvc-serlvet.xml is the result of a picture of the static resource generated here, after which the image is requested.

6. Previously encountered problems and solutions;

At the beginning of this example, I encountered a very strange problem, that is, I upload a file submitted form is the Post method, but he redirected me to get method, and then saved, said there is no get method of the parse function.

My previous index.jsp were as follows:

 

The code for my Uploadcontroller.java is as follows:

package com.kedacom.upload.controller;import java.io.file;import  javax.servlet.http.httpservletrequest;import org.springframework.stereotype.controller;import  Org.springframework.ui.modelmap;import org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.RequestMethod;import  org.springframework.web.bind.annotation.requestparam;import  Org.springframework.web.multipart.MultipartFile, @Controllerpublic  class uploadcontroller {      @RequestMapping (value =  "/upload", method =  Requestmethod.post)     public string upload (          @RequestParam (value =  "file",  required = false)  MultipartFile  File,        httpservletrequest request, modelmap model ) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp; system.out.println ("Start");         string path =  request.getsession (). Getservletcontext (). Getrealpath ("Lupload");         string filename = file.getoriginalfilename ();     SYSTEM.OUT.PRINTLN (path);     file targetfile = new file (path,  FileName);    if  (!targetfile.exists ())  {         targetfile.mkdirs ();    }    //  Save      try {        file.transferto (TargetFile);     } catch  (exception e)  {         E.printstacktrace ();    }         Model.addattribute ("FileUrl",  request.getcontextpath ()  +&nbsP; " /lupload/"+ filename";    return  "result";     }}

The phenomenon is as follows, when I click on the Submit button, upload the file, it is redirected to let me use the Get method to request the/upload method. Seems to be the system to take the redirect, I changed a path/saveuploads, just fine. Question, is this path (/upload) occupied by the system?
I tried it again at night and it was weird.

Simple examples of spring MVC upload files and considerations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.