您可以通过添加一个附加的Filter来捕获异常并重定向到错误页面来处理MaxUploadSizeExceededException。例如,您可以创建一个MultipartExceptionHandler过滤器,如下所示:
public class MultipartExceptionHandler extends oncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { filterChain.doFilter(request, response); } catch (MaxUploadSizeExceededException e) { handle(request, response, e); } catch (ServletException e) { if(e.getRootCause() instanceof MaxUploadSizeExceededException) { handle(request, response, (MaxUploadSizeExceededException) e.getRootCause()); } else { throw e; } } } private void handle(HttpServletRequest request, HttpServletResponse response, MaxUploadSizeExceededException e) throws ServletException, IOException { String redirect = UrlUtils.buildFullRequestUrl(request) + "?error"; response.sendRedirect(redirect); }}注意
:此重定向假设您的表单和上载。您可能需要修改重定向到的位置。具体来说,如果您遵循GET模式下的表单模式,并且在POST上对其进行处理,那么它将起作用。
然后,您可以确保在MultipartFilter之前添加此过滤器。例如,如果您使用的是web.xml,则会看到以下内容:
<filter> <filter-name>meh</filter-name> <filter-class>org.example.web.MultipartExceptionHandler</filter-class></filter><filter> <description> Allows the application to accept multipart file data. </description> <display-name>springMultipartFilter</display-name> <filter-name>springMultipartFilter</filter-name> <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class> <!--init-param> <param-name>multipartResolverBeanName</param-name> <param-value>multipartResolver</param-value> </init-param--></filter><filter> <description> Secures access to web resources using the Spring Security framework. </description> <display-name>springSecurityFilterChain</display-name> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping> <filter-name>meh</filter-name> <url-pattern>/*</url-pattern></filter-mapping><filter-mapping> <filter-name>springMultipartFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping><filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>ERROR</dispatcher> <dispatcher>REQUEST</dispatcher></filter-mapping>
然后,在表单中,您可以通过检查HTTP参数错误是否存在来检测错误是否发生。例如,在JSP中,您可以执行以下操作:
<c:if test="${param.error != null}"> <p>Failed to upload...too big</p></c:if>PS:我创建了SEC-2614以更新文档以讨论错误处理



