16

On my current page I am using JSTL to check if data is available for my form. Problem I am facing is "if there is no data I am not seeing the text fields either". I can solve it using and tags but that would entail lot of if else if else kind of code all through the page. Can anyone suggest me a better cleaner solution to this problem?

<c:if test="${salesData!=null}">
  <c:if test="${fn:length(salesBundle.salesArea) > 0}">
  <input type="text" id="sales_area" class="salesManagerStyle">
  </c:if>
</c:if>
Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
t0mcat
  • 5,511
  • 19
  • 45
  • 58

2 Answers2

19

You can have multiple conditions in a test.

<c:if test="${salesData != null && fn:length(salesBundle.salesArea) > 0}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>

But you can also use the empty keyword to do both a nullcheck and lengthcheck.

<c:if test="${not empty salesData.salesArea}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>

That's the best what you can get, now. If you need to reuse the same condition elsewhere in the page, then you could also save it by <c:set>.

<c:set var="hasSalesData" value="${not empty salesData.salesArea}" />
...
<c:if test="${hasSalesData}">
    <input type="text" id="sales_area" class="salesManagerStyle">
</c:if>
...
<c:if test="${hasSalesData}">
    Foo
</c:if>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • BalusC, Thanks for the reply. – t0mcat Jun 02 '11 at 20:11
  • Actually just realized, this is still the same c:if. To implement c:choose we still have to go through same amount of statements. Right? – t0mcat Jun 02 '11 at 21:01
  • Yes, basically. That's the payoff. If you were using a MVC framework like JSF, then you could save the ``s by using the `rendered` attribute on the components. E.g. ``. – BalusC Jun 02 '11 at 21:02
  • Thanks BalusC. Anything similar to rendered in Spring MVC? Also can I use c:choose like ??? – t0mcat Jun 02 '11 at 21:07
  • I don't do Spring MVC, so I can't tell from top of head. As to the ``, the condition has to go in a nested ``. See also this question which I by coincidence also answered today: http://stackoverflow.com/questions/6219267/if-else-in-jstl You can have more than one ``s in a single ``, for the case you want an if-elseif-elseif-else. – BalusC Jun 02 '11 at 21:10
0

I try to put as little logic as possible in my web pages,

"The interface tier is relatively free of application processing; windows or web pages forward task request to middle tier" Graig Larman, Applying UML and Patterns third Edition page 575 - Information Systems: The classic Three-tier architecture.

Also do the control/validation at the client level before persisting the data...but I guess if it is legacy and web pages are the only things you can touch ...this makes sens

Jules0707
  • 605
  • 7
  • 3