gpt4 book ai didi

spring-mvc - 将 Spring 3 @ExceptionHandler 与公共(public) FileUpload 和 SizeLimitExceededException/MaxUploadSizeExceededException 一起使用

转载 作者:行者123 更新时间:2023-12-03 13:35:24 33 4
gpt4 key购买 nike

我无法捕捉和优雅地处理公共(public)文件上传的 FileUploadBase.SizeLimitExceededException或 Spring 的MaxUploadSizeExceededException上传大文件时。

据我所知,这些异常是在数据绑定(bind)期间引发的,在实际到达 Controller 之前,因此导致 500 并且没有调用异常处理程序方法。以前有没有人遇到过这种情况,正确处理这些异常的最佳方法是什么?

最佳答案

感谢 thetoolman 提供了这个简单的解决方案。我把它延长了一点。我想保持文件处理不变并将异常传输到 Controller 。

package myCompany; 

public class DropOversizeFilesMultipartResolver extends CommonsMultipartResolver {

/**
* Parse the given servlet request, resolving its multipart elements.
*
* Thanks Alexander Semenov @ http://forum.springsource.org/showthread.php?62586
*
* @param request
* the request to parse
* @return the parsing result
*/
@Override
protected MultipartParsingResult parseRequest(final HttpServletRequest request) {

String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);

List fileItems;

try {
fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
} catch (FileUploadBase.SizeLimitExceededException ex) {
request.setAttribute(EXCEPTION_KEY, ex);
fileItems = Collections.EMPTY_LIST;
} catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}

return parseFileItems(fileItems, encoding);
}
}

并在 Controller 中
  @InitBinder("fileForm")
protected void initBinderDesignForm(WebDataBinder binder) {
binder.setValidator(new FileFormValidator());
}

@RequestMapping(value = "/my/mapping", method = RequestMethod.POST)
public ModelAndView acceptFile(HttpServletRequest request, Model model, FormData formData,
BindingResult result) {

Object exception = request.getAttribute(DropOversizeFilesMultipartResolver.EXCEPTION_KEY);
if (exception != null && FileUploadBase.SizeLimitExceededException.class.equals(exception.getClass())) {
result.rejectValue("file", "<your.message.key>");
LOGGER.error(exception);
}

Spring 配置保持不变。将异常传输到验证器会非常好,但我还没有弄清楚如何做到这一点。

关于spring-mvc - 将 Spring 3 @ExceptionHandler 与公共(public) FileUpload 和 SizeLimitExceededException/MaxUploadSizeExceededException 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029583/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com