What type should Struts ActionForm properties be?
Asked Answered
E

2

6

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?

Eagan answered 16/10, 2008 at 17:19 Comment(0)
T
5

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.

Totalizator answered 16/10, 2008 at 17:35 Comment(0)
I
3

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.

Iced answered 16/10, 2008 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.