SPRINGMVC global file Upload type limit "ultimate Solution"

Source: Internet
Author: User
Tags rfc

Dear friends, have you ever encountered this situation, in the information security increasingly attention to the present, the white hat more and more, the corresponding as a developer of security awareness is also growing. However, there will always be a variety of reasons, the overall systemic problems, you can not solve, or do not know. What to do? No way, only return to the essence.

Share today a SPRINGMVC global file upload type Limit ultimate solution for those who are still confused about how to handle the global file upload vulnerability to send a small gift to the small partner. Before reading my code, take a look at one of the following blog posts about Springmvc file uploads. Blog Address http://exceptioneye.iteye.com/blog/1314958

    The client browser will encode the submitted form content in the format specified in RFC 1867, which only needs to decode the information in the request according to the format specified in RFC 1867 to obtain the data submitted by the client form, including the uploaded file. Since the rules set out in RFC 1867 are certain, it is not necessary for us to analyze the information in each request each time according to this rule. Since it is a generic logic, there are, of course, generic libraries, such as the early JSP smart upload and OReilly's COS class libraries, and the Commons FileUpload class libraries that are now used the most.         In real-world development, we only need to upload the processing class library with these specially designed files for the form. In the actual form-based file upload feature, the Spring MVC framework is actually using the above libraries.         However, with the abstraction of the Org.springframework.web.multipart.MultipartResolver interface, Spring MVC leaves us with the right to choose which class library to use. Multipartresolver is located in handlermapping before the request is submitted to it for processing. When a WEB request arrives at Dispatcherservlet and waits for processing, Dispatcherservlet first checks to see if a name called Multipartresolver is found from the Webapplicationcontext. The Multipartresolver instance of the Dispatcherservlet constant Multipart_resolver_bean_name determined). If you can get an instance of Multipartresolver, Dispatcherservlet will call Multipartresolver's Ismultipart (Request) method to check whether the current WEB request is The multipart type. If so, Dispatcherservlet will call the Multipartresolver's Resolvemultipart (Request) method, decorate the original request, and return a Multiparthttpservletrequest for subsequent process use (the original httpservletrequest was rescue into the MULTIPARTHTTpservletrequest), otherwise, return directly to the original HttpServletRequest.  Take a look at UML class diagrams:


After all, Multipartrequest is an interface, interface is an interface, somebody has to achieve. Abstractmultiparthttpservletrequest this abstract class holds multivaluemap<string, multipartfile> multipartFiles Such an instance variable, with this Map, it is not difficult to implement the methods in the Multipartrequest interface. Now the question is, where did multipartfiles come from? It's impossible to pop out of the stone like Monkey king ...         and back to Multipartresolver. The Multipartresolver Ismultipart (Request) method is well implemented, and when it is determined that the current request is a multipart type, it will invoke Multipartresolve's Resolvemultipart (Request). The request here is the original HttpServletRequest object, where miracles occur. Take Commonsmultipartresolver as an example, when calling Resolvemultipart (request), see how it creates multipartrequest:


  1. public  multiparthttpservletrequest resolvemultipart (final  httpservletrequest request)  throws  multipartexception {  
  2. Assert.notnull (Request, "Request must not is null");
  3. if (this. resolvelazily) {
  4. return New Defaultmultiparthttpservletrequest (Request) {
  5. @Override
  6. protected void Initializemultipart () {
  7. Multipartparsingresult Parsingresult = parserequest (request);
  8. Setmultipartfiles (Parsingresult.getmultipartfiles ());
  9. Setmultipartparameters (Parsingresult.getmultipartparameters ());
  10. }
  11. };
  12. }
  13. Else {
  14. Multipartparsingresult Parsingresult = parserequest (request);
  15. return New Defaultmultiparthttpservletrequest (
  16. Request, Parsingresult.getmultipartfiles (), parsingresult.getmultipartparameters ());
  17. }
  18. }

Ok. The rest of the content, please move to the corresponding article.

To achieve a global file upload limit, you might think of two things first. Yes, that's the filter and the Interceptor. However, the filter played for half a day Also

The interception method is implemented with interceptors because the expected results are not achieved.

Nonsense don't say directly on the code

SPRINGMVC Interceptor Configuration:

Note: If your file upload request is very special, try to compress the interception range, otherwise it may affect the user experience.

  <mvc:interceptor>        <mvc:mapping path= "/public/mypath/**/*"/>        <bean class= " X.x.fileshellinterceptor "></bean>  </mvc:interceptor>

SPRINGMVC Request Interceptor:

public class Fileshellinterceptor extends handlerinterceptoradapter{@Overridepublic boolean prehandle ( HttpServletRequest request,httpservletresponse response, Object handler) throws Exception {HttpServletRequest req= ( HttpServletRequest) Request; Multipartresolver res=new org.springframework.web.multipart.commons.CommonsMultipartResolver (); if ( Res.ismultipart (req)) {//system.out.println ("I am a file upload request"); Multiparthttpservletrequest multipartrequest= (multiparthttpservletrequest) req; Map<string, multipartfile> files= multipartrequest.getfilemap ();iterator<string> Iterator = Files.keySet (). iterator (), while (Iterator.hasnext ()) {String Formkey = (string) iterator.next ();//system.out.println ("Form key:" + Formkey); Multipartfile multipartfile = Multipartrequest.getfile (Formkey); Validateutils.isempty (Multipartfile.getoriginalfilename ())) {String filename = fileutils.getdatefilename ( Multipartfile.getoriginalfilename ());//system.out.println ("I am a File" +multipartfile.getoriginalfilename ()); if (checkFile (filename) {return true;} Else{request.getsession (). removeattribute (Global.session_admin_username); Httputils.setactionmessage (Request, "Dear Administrator, your login information has expired, please login again!") ", Action_msg_type. ERROR, True); String Redirecturl=request.getcontextpath () + "/admin/login.jspx";//resolves the issue where the login page appears in frame. Httputils.write2client (Response, "
All right. Friday, we can all go home for the weekend safely.


Original address: http://blog.csdn.net/zgs_shmily/article/details/45917527

Original address: http://blog.csdn.net/zgs_shmily/article/details/45917527

SPRINGMVC global file Upload type limit "ultimate Solution"

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.