Reputation: 810
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.
Upvotes: 0
Views: 2371
Reputation: 1108537
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)
Upvotes: 1
Reputation: 4935
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%>
Upvotes: 0
Reputation: 8530
if(object1!=null){
do something
}else{
do something else
}
possible duplicate Avoiding != null statements
Upvotes: 0