What type should Struts ActionForm properties be?

不羁的心 提交于 2020-01-14 08:53:06

问题


I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding ActionForms. Some of them have only String properties (even for numbers), some of them use the seemingly appropriate types (Integer, Date, String, etc). What's the best practice here?

Also, it seems that if a property is of type Integer, and the value the user entered is not an integer value, Struts silently swallows this and just doesn't set the property. What's up with this?


回答1:


For Struts 1.2x, properties where the user enters or selects values on the HTML form and that are populated on the ActionForm instance automatically by the Struts HTML tags must be Strings or booleans. However, there's no reason why your ActionForm can't have getter methods that return the properties as more meaningful types for your application e.g. Date.




回答2:


If you want to do some validation yourself (or use the struts validator features that have been refactored out of struts later than 1.2) you'll need String properties for exactly the reason that you cite: Once you store numerical values in Integer or int values, they must be either numbers or "nothing at all" - otherwise: how'd you store "a lot" (literally) in an Integer property?

Client Side Validation (e.g. in Javascript) would still work, but you don't want to rely on this.

If - upon entering an invalid number - you are fine with the user being presented a blank field, you may store values in Date-, Integer-, Whatever-Properties. If you'd like to present the original value with the error message, you'll need the String property.

This has the price that you need to do the conversion manually. As Struts 1.2 is quite old you might want to think about gradually replacing your application infrastructure with more modern technology and operate on two technologies (the old & the new) at the same time for a while until the old part gets small enough (or unimportant enough) to be dropped.

nb - you also get more control about what values you want to accept as numbers. I still remember an old Struts creditcard-banking-application in which I asked my manager what the expected outcome is when you'd like to withdraw 3e2 Euro from your card. They didn't say 300 (as Struts converted) but opted for an error.



来源:https://stackoverflow.com/questions/209493/what-type-should-struts-actionform-properties-be

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