开发者

Struts2 converting empty string parameter to an "int"

How does one convert an empty string to an int using Struts2. Wh开发者_运维问答en 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?


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜