有关struts.messages.error.file.too.large和struts.messages.upload.error.SizeLimitExceededException的讨论总结

有关maximumSize与struts.multipart.maxSize的分析


今天在尝试Struts2框架中上传文件功能时无意间发现一处与意向中不太一样的情况。一开始想做自定义的错误信息输出总是失败,才发现struts2关于文件大小超出的错误信息由两种规定。

首先附上这两个变量的配置写法:

例:

maximumSize

<action name="FileUpload" class="cn.timefly.strutsTest.FileUploadAction">

    <result name="success">/FileUploadResult.jsp</result>

    <result name="input">/FileUpload.jsp</result>

    <interceptor-ref name="fileUpload">

      <param name="maximumSize">500000</param>

      <param name="allowedTypes">application/vnd.ms-powerpoint</param>     

    </interceptor-ref>

<interceptor-ref name="defaultStack" />

</action>

struts.multipart.maxSize

<constant name="struts.multipart.maxSize" value="9000000"/>

分析如下:


以下为struts2中struts-message.properties文件的官方文档

有关struts.messages.error.file.too.large和struts.messages.upload.error.SizeLimitExceededException的讨论总结


其中可以看出对于maxSize与maximumSize两个变量是有两种不同的错误信息抛出的。

struts.messages.error.file.too.large  

Occurs when the uploaded file is too large as specified by maximumSize. 

当上传的文件过大(如maximumSize所指定的那样)时发生

 

struts.messages.upload.error.SizeLimitExceededException 

Occurs when the upload request (as a whole) exceed configured struts.multipart.maxSize

当上传请求(作为一个整体)超过配置的struts.multipart.maxSize时发生

 

而Struts2对这两个配置的拦截处理也不相同:

struts.messages.error.file.too.large=File {0} is too large to be uploaded. Maximum allowed size is {4} bytes!

struts.messages.upload.error.SizeLimitExceededException=Request exceeded allowed size limit! Max size allowed is: {0} but request was: {1}!


当我不对这两个变量在框架中配置时,默认的struts.multipart.maxSize2M大小,当我在上传一个大于2M的文件时,拦截到的错误信息是struts.messages.upload.error.SizeLimitExceededException

而struts.multipart.maxSize掌控整个项目所上传文件的最大的Size。超过了这个size,后台报错,程序处理不了如此大的文件。fielderror里面会有如下的提示:

Request exceeded allowed size limit! Max size allowed is: {0} but request was: {1}!

如果我们需要对这两个参数进行配置,应当遵循以下规则

1.fileUpload拦截器的maximumSize属性必须小于struts.multipart.maxSize的值。

2.struts.multipart.maxSize默认2M,当maximumSize大于2M时,必须设置struts.multipart.maxSize的值大于maximumSize。

3.当上传的文件大于struts.multipart.maxSize时,系统报错,当上传的文件在struts.multipart.maxSize和maximumSize之间时,系统提示:

File {0} is too large to be uploaded. Maximum allowed size is {4} bytes!

4.所以上传文件大小应 < maximumSize < maxSize,才可以上传成功。


总结:在配置两个变量时应该注意相应的大小关系,并且当有需求进行自定义错误信息提示时,也需要看一下struts抛出的是哪种类型的错误。切不可像笔者一样不注意错误,盲目的修改提示信息却无法应用。