Tuesday, September 04, 2007

Struts 2 does not like mathematical operators in attribute names

If mathematical operators (+, -, *, /) are made part of an attribute name then Struts 2 may mis-interpret them during lookups. Say if one uses "user-name" as attribute name for storing an object in request scope. On attempt of retrieving this variable from request scope using-

request.getAttribute("user-name");

if Struts 2 does not find this variable in request scope then it looks in ValueStack using OGNL. The OGNL interprets "user-name" as an expression something like ${user - name} and looks for two attributes "user" & "name" and returns difference of value of "user" and "name". This will lead to ClassCastException in your code when you do something like-

User user = (User) request.getAttribute("user-name");

because Struts 2 will return a BigInteger.

Moral of the story, never use mathematical operators in attribute names at least with Struts 2 and of course with JSTL also.