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

Source: Internet
Author: User
Tags tomcat server

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 Commonsmultipartresolver in Springmvc-config.xml, the example is as follows:

<!--config file upload type resolver multipartresolver--><bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">    <!--set the maximum size of the uploaded file, in B    -- <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:

<!--1. In the file upload parsing found an exception, at this time has not entered into the controller method--><bean id= "Exceptionresolver" class= " Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver ">     <property name=" Exceptionmappings ">         <props>         <!--encounter 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 class Exceptionhandler implements handlerexceptionresolver{    /**     * Processing upload file size exceeds limit thrown exception     *    /@Override public    Modelandview resolveexception (httpservletrequest req,            httpservletresponse Res , Object ob,exception ex) {        modelandview mv=new modelandview ();        Judge the exception type to jump to different page        if (ex instanceof maxuploadsizeexceededexception) {             //Specify error message            mv.addobject (" ErrorMessage "," Upload file too large ");            Set Jump View            mv.setviewname ("Useredit");            return mv;        }          Other exception        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--><bean class= "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's bug report mentioned this bug, you can refer to the link: https://bz.apache.org/bugzilla/show_bug.cgi?id= 57438. In the article, it is possible that this is a problem with the Tomcat server, rather than the spring MVC framework, and this problem does not exist if you use the tomcat7.0.39 version.

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:

First, when you configure the file parser, you do not use the file upload size restriction attribute provided by spring MVC <property name= "maxuploadsize" value= "5242880"/>, as 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 class Fileuploadinterceptor extends Handlerinterceptoradapter {    private long maxSize;    @Override Public    Boolean prehandle (httpservletrequest request, httpservletresponse response, Object handler) Throws Exception {
Determine if File upload if (request!=null && servletfileupload. Ismultipartcontent(Request) { Servletrequestcontext ctx = new Servletrequestcontext (request);
Get upload file size size long requestsize = Ctx.contentlength (); if (Requestsize > MaxSize) {
When the upload file size exceeds the specified size limit, the impersonation throws Maxuploadsizeexceededexception exception throw new Maxuploadsizeexceededexception (maxSize); } } return true; } public void Setmaxsize (long maxSize) { 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= "/**"/>        <bean class= " 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 class Filetypeinterceptor extends Handlerinterceptoradapter {@Override public boolean Preh Andle (HttpServletRequest request, httpservletresponse response, Object handler) throws Exception {Boole        An flag= true; Determine if the file upload request if (Request instanceof Multiparthttpservletrequest) {multiparthttpservletrequest Multipa            Rtrequest = (multiparthttpservletrequest) request;            Map<string, multipartfile> files = Multipartrequest.getfilemap ();            iterator<string> Iterator = Files.keyset (). Iterator ();                The multipart request resource is traversed while (Iterator.hasnext ()) {String Formkey = (string) iterator.next ();                Multipartfile multipartfile = Multipartrequest.getfile (Formkey);                String Filename=multipartfile.getoriginalfilename (); Determine if file type I is restrictedF (! checkfile (filename)) {//Limit file type, request forward to the original request page, and carry error message Request.setattribute ("Err Ormessage "," Unsupported file Types!                    ");                     Request.getrequestdispatcher ("/web-inf/jsp/useredit.jsp"). Forward (request, response);                Flag= false;    }}} return flag; }/** * Determines whether the allowed upload file type, true means allow */private Boolean checkfile (String fileName) {//Set Allow upload file type S        Tring suffixlist = "Jpg,gif,png,ico,bmp,jpeg";                Get file suffix String 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.

Forwarded from: https://www.cnblogs.com/com-itheima-crazyStone/p/6807342.html

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.