Handling MaxUploadSizeExceededException with Spring MVC

给你一囗甜甜゛ 提交于 2020-02-01 05:28:05

问题


How can I intercept and send custom error messages with file upload when file size is exceeded. I have an annotated exception handler in the controller class, but the request does not come to the controller. The answer I came across on this link How to handle MaxUploadSizeExceededException suggests implementing HandlerExceptionResolver.

Have things changed in Spring 3.5 or is that still the only solution?


回答1:


I ended up implementing 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;
}

}



来源:https://stackoverflow.com/questions/8999572/handling-maxuploadsizeexceededexception-with-spring-mvc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!