spring MVC上传文件使用了common.fileupload组件,该组件上传文件的时候有个文件大小的限制,在超出这个限制之后.会抛出MaxUploadSizeExceededException异常.
该异常是spring检查上传文件的信息的时候抛出的,此时还没进入Controller内解析文件的方法中.
网上查到的方法全是
1 使用org.springframework.web.servlet.handler.SimpleMappingExceptionResolver,如:
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">2 自己实现.HandlerExceptionResolver类,如
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">maxUploadExceeded</prop>
</props>
</property>
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
private Log log = LogFactory.getLog(getClass());
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
log.warn("Handle exception: " + ex.getClass().getName());
Map model = new HashMap();
model.put("ex", ex.getClass().getSimpleName());
model.put("error", ex.getMessage());
return new ModelAndView("error", model);
}
另定义<bean class="MyHandlerExceptionResolver "/>
这两种方法的侵入性真的太大了,查看源代码org.springframework.web.multipart.commons.CommonsMultipartResolver 127行
if (this.resolveLazily) {
return new DefaultMultipartHttpServletRequest(request) {
@Override
protected void initializeMultipart() {
MultipartParsingResult parsingResult = parseRequest(request);
setMultipartFiles(parsingResult.getMultipartFiles());
setMultipartParameters(parsingResult.getMultipartParameters());
}
};
}
有个resolveLazily属性,一个类似懒加载的属性.可以定义该属性.让解析文件的时候再抛异常,然后Controller中定义异常处理的方法
<bean id="multipartResolver"定义异常处理的方法
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" >
<property name="resolveLazily" value="true"/>
<property name="maxUploadSize" value="1024" />
</bean>
@ExceptionHandler(Exception.class)
public String handleException(Exception ex,HttpServletRequest request) {
if(ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException){
request.setAttribute("error", "文件超过长度");
}
return "要转向的页面,可以*定义或者是原页面.";
}
时间关系.具体原因可以查看spring 源代码.