0

I want to use JSP page to return dynamic xml.The problem I'm facing is that I've model where some values are null and when they are null I don't wont to display them. So I can do following:

if(ampApInfo.getColourcd().equals(null)){   %>

    <ColourCd><%=  ampApInfo.getColourcd() %></ColourCd>

  <%} else if(ampApInfo.getSzWeightColourcd().equals(null)){ %> 


    <SzWeightColourcd><%= ampApInfo.getSzWeightColourcd()  %></SzWeightColourcd>

  <%}%> //and so forth

But this makes my code ugly and not practical. Is there a way to avoid that?? Can you please provide me with an example how to do it or point to one. Thanks a lot.

James Jithin
  • 10,183
  • 5
  • 36
  • 51
user1048282
  • 780
  • 1
  • 9
  • 22

3 Answers3

1

The ugliness is caused by using old fashioned scriptlets instead of JSTL/EL. With JSTL, it would look more self-documenting (as it uses XML-like markup). With EL you can use the ${} notation to access bean properties.

Something like this:

<c:choose>
    <c:when test="${not empty ampApInfo.colourcd}">
        <ColourCd>${ampApInfo.colourcd}</ColourCd>
    </c:when>
    <c:when test="${not empty ampApInfo.szWeightColourcd}">
        <ColourCd>${ampApInfo.szWeightColourcd}</ColourCd>
    </c:when>
    <c:otherwise />
</c:choose>

(note that I inversed the condition, you were printing the elements when the value is null, which contradicts your own functional requirement)

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

if(object1!=null){

do something

}else{

do something else

}

possible duplicate Avoiding != null statements

Community
  • 1
  • 1
Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
  • It is similar by not exactly what I wanted. I've looked in to it before I've posted this question and no help :/ – user1048282 Jan 25 '12 at 12:23
0

Try ternary operator. Also, I think, you have missed not of in your code, so if your code is,

     if(ampApInfo.getColourcd() != null){   %>

    <ColourCd><%=  ampApInfo.getColourcd() %></ColourCd>

  <%} else if(ampApInfo.getSzWeightColourcd() != null){ %> 

    <SzWeightColourcd><%= ampApInfo.getSzWeightColourcd()  %></SzWeightColourcd>

  <%}%> //and so forth

then, you shall transform to like this.

<%
    String str1 = "tag1 data";
    String str2 = "tag2 data";
    String finalStr = str1 != null ? "<tag1>" + str1 + "</tag1>" : (str2 != null ? "<tag2>" + str2 + "</tag2>" : "");
%>
  <%= finalStr%>
Vaandu
  • 4,857
  • 12
  • 49
  • 75