【问题标题】:Handling MaxUploadSizeExceededException with Spring MVC使用 Spring MVC 处理 MaxUploadSizeExceededException
【发布时间】:2012-02-18 10:50:25
【问题描述】:

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

在 Spring 3.5 中发生了什么变化,还是那仍然是唯一的解决方案?

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    我最终实现了 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;
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 2011-02-11
      • 2012-12-27
      • 2014-07-14
      • 2021-09-18
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多