Search code examples
jspparametersstruts2ognlstruts-tags

OGNL/Struts2 JSP assigning bean to an object


In Struts2 / OGNL page, is it possible to assign any type of bean to an object depending on condition?

For instance,

  <s:if test"%{customer != null}">
       <s:set var="someobject" value="customer">
  </s:if>
  <s:else>
       <s:set var="someobject" value="user">
  </s:else>

Solution

  • Yes, you can. But are you sure you should ?

    This seems to be business, not presentation, and hence why in the view and not in the controller ?

    Instead of

    <s:if test"%{customer != null}">
         <s:set var="someobject" value="customer">
    </s:if>
    <s:else>
         <s:set var="someobject" value="user">
    </s:else>
    
    SomeObject is of type : <s:property value="%{#someobject.class.name}" />
    

    You can use in your action

    public String getSomeobject(){
        return (customer!=null) ? customer : user;
    }
    

    and in JSP only

    SomeObject is of type : <s:property value="%{someobject.class.name}" />
    

    Your use case is more suitable when your action knows nothing about your objects, but then you would be putting a lot of business logic in the view...