How can I set a property value of a different type than String?

I have bean with properties that are of other types than String. How can I set these properties using <jsp:setProperty>? How about a non-String attribute value for a custom action?
Answer:
If you use a literal string as the attribute value, such as

<jsp:setProperty name="foo" property="bar" value="value1" />

the JSP container looks at the type of the corresponding property in the bean class to see if the value needs to be converted. If the property is of type boolean, Boolean, byte, Byte, char, Character, double, Double, int, Integer, float, Float, long or Long, it will try to convert the string value to the correct type for the property. If the property is a String, the value is of course used as is. If it’s something else, you get a translation-time error.

If you need to set a property that is not one of the types listed above, for instance a java.util.Date, you must to use a request-time attribute value in JSP 1.1, such as

<jsp:setProperty name="foo" property="bar"
  value="<%= new java.util.Date() %>" />

When you use a request-time attribute value, the JSP container does not attempt to do any type conversion. In other words, the type of the expression must match the type of the corresponding bean property. In JSP 1.2, it’s possible to associate a so called “JavaBeans property editor” with the bean to convert string values to complex types like Date. I describe this approach in the second edition of the book.

The bean conversion rules apply to attribute values in custom actions: literal String values are converted to the type of the corresponding property in the tag handler class if it’s one of the types listed above, and for other types you can use a request-time attribute value, or in JSP 1.2, create a property editor that knows how to convert strings to complex data types.

Leave a Reply

Your email address will not be published. Required fields are marked *