views:

362

answers:

1

I'm using Spring Web Flow (v. 1.0.5) and I have a JSP page that makes an AJAX call to a flow and needs to read in the XML results. That flow successfully sets an object into the FlowScope, then calls a JSP page to render the results. In the JSP page, I'd like to test whether the object has a property (say, .firstName) and if so, do something. I can access the variable in the FlowScope using JSTL expression language (by saying ${userObj}), but that just lets me spit it out. I've tried the methods below to get at it and put logic around it, with varying success.

Update: The remaining question is: How do I get the context and flow scope in the scriptlet (<% %>) section?

<rootnode>

<!--  Attempt 1:  c:if isn't being interpreted (though ${userObj.firstName} is),
      it's just displaying the tags on the page. -->
<!--  Update, I didn't have the <%@ taglib directive for jstl/core.  
      Now I do, and they're being interpreted, but it says 
         "According to TLD or attribute directive in tag file,
          attribute test does not accept any expressions"
      How can the if/@test not accept expressions?  Isn't that its whole purpose
      in life? -->
<!--  Update 2, I also forgot the taglib for the rt language, which is separate,
      I guess (jstl/core_rt).  <c:if test now works properly. -->
<c:if test="${!empty(userObj.firstName)}">
<test>not empty</test>
</c:if>

<%
/* Attempt 2:  This throws an error, can't resolve "context".  How do I get the context? */
if (context.getFlowScope().userObj != null) {
    out.write("not null");
} else {
    out.write("not not null");
}
%>

<!--  Attempt 3:  This works, I get the reference to the Object and it
      spits out the correct firstName, gives me no control other than
      spitting out the value. -->
<userReference>${userObj}</userReference>
<userReference_firstName>${userObj.firstName}</userReference_firstName>

</rootnode>
+2  A: 

Attempt 1 should work if you installed JSTL and declared the taglib the right way and declared the web.xml to be at least Servlet 2.4. Also see this answer and this answer. To test if an object is empty or not, you should rather use the following construct:

<c:if test="${not empty userObj.firstName}">

or

<c:if test="${userObj.firstName != null}">

Attempt 2 is strongly discouraged. Scriptlers are a poor practice and should always be replaced by taglibs like JSTL and EL (as you did in attempt 1). If it's not possible for technical reasons, then the coding ought to be done in a real Java class, (indirectly) starting with a Servlet.

Attempt 3 is doable, but I would recommend to use servlet with a Javabean-to-XML serializer like XStream instead. This way you can just feed a collection of Javabeans to the outputstream of the response transparently.

BalusC