How to nicely handle file upload MaxUploadSizeExceededException with Spring Security

前端 未结 4 1742
梦如初夏
梦如初夏 2020-12-05 05:20

I\'m using Spring Web 4.0.5, Spring Security 3.2.4, Commons FileUpload 1.3.1, Tomcat 7 and I\'m getting an ugly MaxUploadSizeExceededException when my upload si

4条回答
  •  没有蜡笔的小新
    2020-12-05 06:02

    I know I'm late to the party, but I found a much more elegant solution imho.

    Instead of adding a filter for the multipart resolver, simply add throws MaxUploadSizeExceededException on your controller method and add the filter for the DelegatingFilterProxy in your web.xml and you can add an exception handler right in your controller without having to redirect the request.

    e.g.:

    Method (in Controller):

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public ResponseEntity uploadFile(MultipartHttpServletRequest request) throws MaxUploadSizeExceededException {
        //code
    }
    

    Exception Handler (in same controller):

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity handleSizeExceededException(HttpServletRequest request, Exception ex) {
        //code
    }
    

    Web.xml (thanks to Rob Winch):

    
        
            Secures access to web resources using the Spring Security framework.
        
        springSecurityFilterChain
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
    
    
        springSecurityFilterChain
        /*
        ERROR
        REQUEST
    
    

    And that is all you need.

提交回复
热议问题