views:

426

answers:

2

How does one convert an empty string to an int using Struts2. When the application encounters this parameter with no value, like from an empty text field, it throws the following exception.

java.lang.NoSuchMethodException:
com.XXXXXXXXXXXX.setID([Ljava.lang.String;)

Where ID is an integer, and the URL is:

Something.action?ID=&other=rawr

Is there a way to do this without using an Integer (class)? Do I have to write a type converter?

+3  A: 

If you declare your id parameter as Integer struts will convert the empty string to null.

public void setId(Integer id){ 
...
}

From : http://struts.apache.org/2.0.14/docs/type-conversion.html#TypeConversion-NullandBlankValues

Null and Blank Values

Some properties cannot be set to null. Primitives like boolean and int cannot be null. If your action needs to or will accept null or blank values, use the object equivalents Boolean and Integer. Similarly, a blank string "" cannot be set on a primitive. At the time of writing, a blank string also cannot be set on a BigDecimal or BigInteger. Use server-side validation to prevent invalid values from being set on your properties (or handle the conversion errors appropriately).

Ash Kim
Oh - I just saw you are already aware of this... Integer's no good?What int value would a "" be converted to? 0? -1? some known constant?
Ash Kim
+1  A: 

I don't know why you don't like to use Integer in the first place. However, you can have your set method as,

public void setId(String id) {
     ....             // convert your string to int here, as you wish
     this.id = intId; // 
}

If you are having some defaults. You can make use of commons-lang StringUtils.defaultIfEmpty(...) method.

The accessor would still be public int getId(){...}. Try this out.

Adeel Ansari
Be careful, sometimes using different types for the setter and getter can confuse OGNL. If so, you might need to have getId() return a String too.
Todd Owen
Thanks for the link. I was trying to find a more general solution, because we use "int" all over the application and I was hoping to not have to convert all of them to Integer.Can I keep the member as an "int" but write a setId(Integer id) method?
partkyle
"Can I keep the member as an "int" but write a setId(Integer id) method?" You can, but ask yourself what would happen if `setId(null)` is called.
leonbloy
@Kyle Partridge: I would like you to look at this thread here http://stackoverflow.com/questions/423704/java-int-or-integer/423718#423718 . Actually, its about which is better `int` or `Integer` in some particular scenario.
Adeel Ansari