春のMVC - 最大アップロードサイズを処理する方法が例外を超えました

Spring MVC –最大アップロードサイズ超過例外の処理方法

Springでは、@ControllerAdviceを宣言して、次のような醜い最大アップロードサイズ超過例外をキャッチできます。

spring-file-upload-max-file-size

溶液

multipartResolverのタイプによって異なります:

  1. StandardServletMultipartResolverMultipartExceptionをキャッチします。this exampleを参照してください。

  2. CommonsMultipartResolverMaxUploadSizeExceededExceptionをキャッチ–this exampleを参照します。

GlobalExceptionHandler.java

package com.example.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler {

    //StandardServletMultipartResolver
    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";

    }

    //CommonsMultipartResolver
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public String handleError2(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";

    }

}

Tomcat Connection Reset
Tomcatにデプロイし、ファイルサイズ超過の例外をキャッチできない場合、TomcatのmaxSwallowSize設定が原因である可能性があります。 これを読んでください–Spring file upload and connection reset issue