SPRINGMVC Study Summary (v)--springmvc File Upload Example

Source: Internet
Author: User
Tags tomcat server

It's SpringMVC-3.1.1, commons-fileupload-1.2.2 and io-2.0.1.

First, Web. xml

    <?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "http://java.sun.com/xml/n S/javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.co M/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <servlet> <s Ervlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherser          Vlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> &LT;URL-PATTERN&GT;/&L t;/url-pattern> </servlet-mapping> <filter> &LT;FILTER-NAME&GT;SPRINGC Haracterencodingfilter</filter-name> <filter-class>org.springframework.web.filter.characterencodi Ngfilter</filter-clasS> <init-param> <param-name>encoding</param-name> < param-value>utf-8</param-value> </init-param> </filter> <filter-map Ping> <filter-name>SpringCharacterEncodingFilter</filter-name> <url-pattern&gt ;/*</url-pattern> </filter-mapping> <welcome-file-list> <wel   Come-file>/web-inf/jsp/user/add.jsp</welcome-file> </welcome-file-list> </web-app>

 

    <?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" xsi:schemalocation= "Http://www.springframewo                              Rk.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/mvc http://www.springframework.or                               G/schema/mvc/spring-mvc-3.1.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.0.xsd "> &LT;CONTEXT:COMPONENT-SC An base-package= "Com.jadyer"/> <bean class= "Org.springframework.web.servlet.view.InternalResource       Viewresolver ">       <property name= "prefix" value= "/web-inf/jsp/"/> <property name= "suffix" value= ". jsp"/> </bean> <!--springmvc Upload a file, you need to configure the Multipartresolver processor--<bean id= "Multip Artresolver "class=" Org.springframework.web.multipart.commons.CommonsMultipartResolver "> <property name = "Defaultencoding" value= "UTF-8"/> <!--specifies that the total size of the uploaded file cannot exceed 200KB.          Note that the limit for the Maxuploadsize property is not for individual files, but for the sum of the capacity of all Files <property name= "maxuploadsize" value= "200000"/> </bean> <!--Springmvc throws Org.springframework.web.multipart.MaxUploadSizeExceededE when the upload file limit is exceeded Xception-<!--This exception was thrown when Springmvc checked for uploaded file information and was not yet in the Controller method--<bean id= "Excepti Onresolver "class=" Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver "> <property n        Ame= "Exceptionmappings" > <props>              <!--when encountering an maxuploadsizeexceededexception exception, automatically jumps to/web-inf/jsp/error_fileupload.jsp page-- <prop key= "Org.springframework.web.multipart.MaxUploadSizeExceededException" >error_fileupload</prop   > </props> </property> </bean> </beans>

Here is the form page for uploading//web-inf//jsp//user//add.jsp

    <%@ page language= "java" pageencoding= "UTF-8"%>      <form action= "<%=request.getcontextpath ()%>/ User/add "method=" POST "enctype=" Multipart/form-data ">          username: <input type=" text "name=" username "/> <br/>          Nickname: <input type= "text" name= "nickname"/><br/> password          : <input type= " Password "name=" password "/><br/>          yourmail: <input type=" text "name=" email "/><br/>          Yourfile: <input type= "file" Name= "Myfiles"/><br/> yourfile          : <input type= "file" name= "Myfiles"/ ><br/>          yourfile: <input type= "file" Name= "Myfiles"/><br/> <input type=          "Submit" Value= "Add new user"/>      </form>  

Here is the page that prints the user information after the upload is successful//web-inf//jsp//user//list.jsp

    <%@ page language= "java" pageencoding= "UTF-8"%>      <%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl /core "%>      <c:foreach items=" ${users} "var=" user ">          ${user.value.username}----${ User.value.nickname}----${user.value.password}----${user.value.email}              <a href= "<%= Request.getcontextpath ()%>/user/${user.value.username} "> View </a>              <a href=" <%= Request.getcontextpath ()%>/user/${user.value.username}/update "> Edit </a>              <a href=" <%= Request.getcontextpath ()%>/user/${user.value.username}/delete "> Delete </a>          <br/>      </c :foreach>      <br/>      <a href= "<%=request.getcontextpath ()%>/user/add" > Continue adding User </a >  

The following is a hint page when uploading a file is too large//web-inf//jsp//error_fileupload.jsp

<%@ page language= "java" pageencoding= "UTF-8"%>  

The next step is to use the entity class User.java

    Package Com.jadyer.model;            /** *      User      * @author Hongyu      * @create May, 1:24:43 AM */      public      class User {          private String us Ername;          Private String nickname;          private String password;          private String Email;          /*== Four properties of Getter (), setter () slightly ==*/public          user () {} public          User (string username, string nickname, String Password, String email) {              this.username = Username;              This.nickname = nickname;              This.password = password;              This.email = email;          }      }  

and finally, the core Usercontroller.java.

    Package Com.jadyer.controller;      Import Java.io.File;      Import java.io.IOException;      Import Java.util.HashMap;            Import Java.util.Map;            Import Javax.servlet.http.HttpServletRequest;      Import Org.apache.commons.io.FileUtils;      Import Org.springframework.stereotype.Controller;      Import Org.springframework.ui.Model;      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;            Import Com.jadyer.model.User; /** * File Upload in Springmvc * @see The first step: Because SPRINGMVC uses the Commons-fileupload implementation, its components are introduced into the project * @see here is commons- Fileupload-1.2.2.jar and Commons-io-2.0.1.jar * @see Step Two: Configure the Multipartresolver processor in ####-servlet.xml. You can add a property restriction to an uploaded file here * @see Step three: Adding the Multipartfile parameter to the controller's method. This parameter is used to receive the contents of the file component in the form * @see Fourth step:Write a foreground form. Note enctype= "Multipart/form-data" and <input type= "file" name= "* * * *"/> * @author Hongyu * @create May 12, 2012 1:26 : */@Controller @RequestMapping ("/user") public class Usercontroller {private Final St                    atic map<string,user> users = new hashmap<string,user> (); Simulate data source, construct initial data public Usercontroller () {users.put ("Zhang Ling", New User ("Zhang Ling", "stuffy oil bottle", "02200059", "[email&              Nbsp;protected]);              Users.put ("Li Huan", New User ("Li Huan", "Li Tan Hua", "08866659", "[email protected]"));              Users.put ("Extension and Extraction field", New User ("Extension of the Wild", "Search God", "05577759", "[email protected]"));          Users.put ("Monkey King", New User ("Sun Wukong", "Monkey King", "03311159", "[email protected]")); } @RequestMapping ("/list") public String list (model model) {Model.addattribute ("U              Sers ", users);          return "User/list"; } @RequestMapping (value= "/add", Method=requestmethod.get) public String AddUser () {return "User/add"; } @RequestMapping (value= "/add", method=requestmethod.post) public String addUser (user user, @RequestPara M multipartfile[] myfiles, HttpServletRequest request) throws ioexception{//If you just upload a file, you only need the Multipartfile type to receive File, and you do not need to explicitly specify @requestparam annotations//If you want to upload multiple files, you will need to use the multipartfile[] type to receive the file, and also specify @requestparam annotations//And And when uploading multiple files, all <input type= "file"/> in the foreground form should be myfiles, otherwise the myfiles in the parameter cannot get all the uploaded files for (Multipartfile Myfil                  E:myfiles) {if (Myfile.isempty ()) {System.out.println ("File not uploaded");                      }else{System.out.println ("File length:" + myfile.getsize ());                      System.out.println ("File type:" + myfile.getcontenttype ());                      System.out.println ("File name:" + myfile.getname ()); System.out.println ("File formerly known as:" + Myfile.getoriginaLfilename ());                      System.out.println ("========================================"); If you are using a TOMCAT server, the files are uploaded to the \\%tomcat_home%\\webapps\\yourwebproject\\web-inf\\upload\\ folder in String Realpa                      th = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/upload"); There is no need to deal with the problem of Io stream shutdown, because the Fileutils.copyinputstreamtofile () method will automatically shut down the IO stream used, I see it's source code to know Fileutils.copyinputs                  Treamtofile (Myfile.getinputstream (), New File (Realpath, Myfile.getoriginalfilename ()));              }} users.put (User.getusername (), user);          return "Redirect:/user/list";   }      }

Add: Remember to set up this directory for storing uploaded files, i.e.//web-inf//upload//

SPRINGMVC Study Summary (v)--springmvc File Upload Example

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.