使用Spring MVC处理MaxUploadSizeExceededException

时间:2012-01-25 08:14:51

标签: spring-mvc

如果超出文件大小,如何拦截并发送带文件上传的自定义错误消息。我在控制器类中有一个带注释的异常处理程序,但请求不会出现在控制器上。我在这个链接How to handle MaxUploadSizeExceededException上遇到的答案建议实现HandlerExceptionResolver。

Spring 3.5中的内容是否有所改变,还是唯一的解决方案?

1 个答案:

答案 0 :(得分:4)

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

}