gpt4 book ai didi

spring-mvc - 使用 Spring MVC 处理 MaxUploadSizeExceededException

转载 作者:行者123 更新时间:2023-12-01 12:57:21 27 4
gpt4 key购买 nike

当超过文件大小时,如何通过文件上传拦截和发送自定义错误消息。我在 Controller 类中有一个带注释的异常处理程序,但请求没有到达 Controller 。我在这个链接上找到的答案 How to handle MaxUploadSizeExceededException建议实现 HandlerExceptionResolver。

Spring 3.5 有什么变化吗?还是那仍然是唯一的解决方案?

最佳答案

我最终实现了 HandlerExceptionResolver:

@Component public class ExceptionResolverImpl implements HandlerExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionResolverImpl.class);

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception exc) {

if(exc instanceof MaxUploadSizeExceededException) {
response.setContentType("text/html");
response.setStatus(HttpStatus.REQUEST_ENTITY_TOO_LARGE.value());

try {
PrintWriter out = response.getWriter();

Long maxSizeInBytes = ((MaxUploadSizeExceededException) exc).getMaxUploadSize();

String message = "Maximum upload size of " + maxSizeInBytes + " Bytes per attachment exceeded";
//send json response
JSONObject json = new JSONObject();

json.put(REConstants.JSON_KEY_MESSAGE, message);
json.put(REConstants.JSON_KEY_SUCCESS, false);

String body = json.toString();

out.println("<html><body><textarea>" + body + "</textarea></body></html>");

return new ModelAndView();
}
catch (IOException e) {
LOG.error("Error writing to output stream", e);
}
}

//for default behaviour
return null;
}

关于spring-mvc - 使用 Spring MVC 处理 MaxUploadSizeExceededException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8999572/

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