You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSP地址字段拼接问题:处理空值与实现换行需求

Fixing Empty Address Fields and Line Breaks in 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 use fn:trim to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:27:20