File upload size and file type restrictions in Spring MVC environment and large file upload bug issues

Source: Internet
Author: User

In the previous article, we mainly introduced the implementation of the file upload function under normal circumstances under the SPIRNG MVC environment. In the actual development, will also involve the upload file size and type restrictions, the next will be the SPIRNG MVC environment File upload size and type limitations, will also explain the file upload size Tomcat server bug problems and solutions.

One, file upload size limit

This is still the last article introduces the file upload size limit under spring MVC, the file upload size limit can be configured when the file parser is commonsmultipartresolver in Springmvc-config.xml. Examples are as follows:

<!--config file upload type resolver multipartresolver--><bean id="multipartresolverclass="  Org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--set the maximum size of the uploaded file, in units of B--and < Property Name="maxuploadsize" value="5242880"/></bean>   

The limitation on file upload size in spring MVC is as simple as the problem is that spring MVC does not have a configuration like Struts2, and if you simply configure a configuration that restricts file upload size, an exception occurs when the upload limit is exceeded:

So when the file size limit is configured in the file parser, the thrown maxuploadsizeexceededexception(the upload file is too large) must be received and jumped. With regard to exception reception, there are 3 ways that are described in the Spring MVC official documentation, which is mainly about 2 of these:

(1) Use the simplemappingexceptionresolver(Exception resolution Mapper) provided by spring MVC directly in the configuration file Spring-config.xml to receive exception information:

<!--1An exception was found during file upload parsing, which was not yet entered into the controller method--><bean id="Exceptionresolver" class="Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionmappings"> <props> <!--when encountering an maxuploadsizeexceededexception exception, jump to error.jsp page--<prop key= "org.springframework.web.multipart.MaxUploadSizeExceededException" >/error </prop></props> </property></bean>

When the file upload size exception occurs again, the configuration file automatically catches the exception and matches it to the corresponding maxuploadsizeexceededexception exception and jumps to the specified error.jsp error page.

(2) The other is to customize an exception handler class, can match to receive various exceptions, but also can specify the jump page and error message:

/** * Custom Exception handler class*/ Public classExceptionhandler implements handlerexceptionresolver{/** * Processing the upload file size exceeds the limit thrown exception*/@Override PublicModelandview resolveexception (httpservletrequest req, httpservletresponse res, Object ob,exception ex) { Modelandview MV=NewModelandview (); //determine the type of exception to jump to different pages        if(ex instanceof maxuploadsizeexceededexception) {//Specifying error MessagesMv.addobject ("errormessage","upload file too large"); //Set Jump ViewMv.setviewname ("Useredit"); returnMV; }          //Other Exceptions        return NULL; }}

The above custom exception handler class, which simulates receiving the thrown maxuploadsizeexceededexception exception, after completing the custom exception handler class, must also be configured in the Spring-config.xml configuration file:

2. Configure the custom exception handler class--classes="com.itheima.exception.ExceptionHandler" />

The above describes the 2 main spring MVC file upload size limits and exception capture scenarios, the reader can self-test.

Add: File Upload size limit tomcat server bug issue

  After using the above 2 file upload size limit and exception capture configuration, when the upload file size exceeds the limit of a certain range, you can correctly catch the exception and jump to the specified page, but when the upload file is very large (seriously exceeding the upload size limit) , It is possible to have a maxuploadsizeexceededexception dead loop state, when the page crashes directly.

On this anomaly, in the market books, curriculum materials are not mentioned in this point, are deliberately avoided (because the development may be more use of plug-ins for file upload and download, rather than the framework of their own, and this bug problem is not effectively resolved). In response to this problem, the official documents and the relevant information are not clear solutions and problem description. However, in a foreigner bug report mentioned this bug, you can refer to the link:https://bz.apache.org/bugzilla/show_bug.cgi?id=57438; In the article explains This could be a problem with the Tomcat server, not the Spring MVC framework, and if you use the tomcat7.0.39 version, the problem does not exist .

So for the spring MVC file upload size limit This problem, you can swap with the tomcat7.0.39 version of the Tomcat server, or use another way of thinking.

Solutions currently available:

    File Upload size restriction property provided by spring MVC is not used first when you configure the file parser < Span style= "COLOR: #800000" ><property name= "maxuploadsize "Value=" 5242880 "/> , as shown in the following example:

<!--config file upload type resolver multipartresolver--><bean id="multipartresolver"class ="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Then customize an interceptor to limit the file upload size and simulate throwing maxuploadsizeexceededexception exceptions :

 Public classFileuploadinterceptor extends Handlerinterceptoradapter {Private Long maxSize; @Override Publicboolean prehandle (httpservletrequest request, httpservletresponse response, Object handler) throws Exception {
Determine if file uploadif(request!=NULL&&Servletfileupload. ismultipartcontent (request)) {Servletrequestcontext CTX=NewServletrequestcontext (Request);
Get upload file size sizeLongRequestsize =ctx.contentlength (); if(Requestsize >maxSize) {
Impersonation throws a maxuploadsizeexceededexception exception when the upload file size exceeds the specified size limitThrow Newmaxuploadsizeexceededexception (maxSize); } } return true; } Public voidSetmaxsize (LongmaxSize) { This. maxSize =maxSize; }}

Finally, in Spring-config.xml, the interceptor that intercepts the upload size limit is configured:

<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <beanclass="Com.itheima.interceptor.FileUploadInterceptor"> <!--set limit file upload Size-<property name="maxSize"Value=" 5242880"/> </bean> </mvc:interceptor></mvc:interceptors>

This allows you to complete the file upload size restrictions in the spring MVC environment and to correctly capture the exceptions.

Ii. limitations of File Upload types

It is important to state that, in the spring MVC configuration, there is no interceptor configured as in the Struts2 configuration file to limit the size and type of the uploaded file. There is also no solution for restricting file upload types in the spring MVC environment, but we can still use custom interceptors to restrict file upload types in the official documentation and related materials.

First, customize a file upload type-limiting interceptor, as shown in the following example:

/** * Global file Type Interceptor*/ Public classFiletypeinterceptor extends Handlerinterceptoradapter {@Override Publicboolean prehandle (httpservletrequest request, httpservletresponse response, Object handler) throws Excepti On {Boolean flag=true; //determine whether to upload requests for files        if(Request instanceof Multiparthttpservletrequest) {multiparthttpservletrequest multipartrequest=(multiparthttpservletrequest) request; Map<string, multipartfile> files =Multipartrequest.getfilemap (); Iterator<String> iterator =Files.keyset (). iterator (); //traversing multi-part Request Resources             while(Iterator.hasnext ()) {String Formkey=(String) iterator.next (); Multipartfile Multipartfile=Multipartrequest.getfile (Formkey); String filename=Multipartfile.getoriginalfilename (); //determine if the file type is restricted                if(!checkfile (filename)) {                    //restricting file types, forwarding requests to the original request page, and carrying error messagesRequest.setattribute ("errormessage","Unsupported file Types! "); Request.getrequestdispatcher ("/web-inf/jsp/useredit.jsp"). Forward (request, response); Flag=false; }             }        }        returnFlag; }    /** * Determines whether the allowed upload file type, true means allow*/    Privateboolean checkfile (String fileName) {//set allow file types to be uploadedString suffixlist ="Jpg,gif,png,ico,bmp,jpeg"; //get file suffixString suffix = filename.substring (Filename.lastindexof (".")                +1, Filename.length ()); if(Suffixlist.contains (Suffix.trim (). toLowerCase ())) {return true; }        return false; }}

In the above example, the custom interceptor restricts the file upload type to: String suffixlist = "jpg,gif,png,ico,bmp,jpeg",and when the interception succeeds, it returns to the FAR request page and carries the error message.

Then configure the custom interceptor in Spring-config.xml, as shown in the following example:

<mvc:interceptors>
<!--If you have multiple interceptors, configure them in order-
<mvc:interceptor>
<!--/** represents all URLs and child URL paths--
<mvc:mapping path= "/**"/>
<!--Configure a custom file upload type limit blocker--
<bean class= "Com.itheima.interceptor.FileTypeInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

After completing the above steps, limit the file upload type to complete and the reader can test it yourself.

File upload size and file type restrictions in Spring MVC environment and large file upload bug issues

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.