JSP地址字段拼接问题:处理空值与实现换行需求
Let’s tackle your two issues step by step—getting rid of those annoying extra commas and making each valid address line display on its own row.
First, you’ll need to use JSTL (JavaServer Pages Standard Tag Library) for clean conditional logic (it’s the standard way to handle this kind of thing in JSP, no messy scriptlets needed). Start by adding these taglib declarations at the top of your JSP file:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Then, replace your existing <td> code with this:
<td> <c:if test="${not empty fn:trim(addr1)}"> ${fn:trim(addr1)}<br> </c:if> <c:if test="${not empty fn:trim(addr2)}"> ${fn:trim(addr2)}<br> </c:if> <c:if test="${not empty fn:trim(postalCode)}"> ${fn:trim(postalCode)} </c:if> </td>
How this works:
- No extra commas: The
<c:if>tags only render content if the trimmed address field isn’t empty. We usefn:trimto ignore fields that are just whitespace (like a blank string with spaces). - Line breaks: The
<br>tag adds a line break after each valid field. We skip the<br>on the last field to avoid an unnecessary empty line at the end.
If you ever want to go back to using commas instead of line breaks (but still avoid extras), you could collect non-empty fields into a list and join them, but for your current request, the above approach is simple and effective.
内容的提问来源于stack exchange,提问作者sazen Dun

