如何在JSP文件中正确读取并展示Java对象列表的内部属性
原因说明
你直接输出diffOutputList时,JSTL的c:out标签会调用列表中每个DiffOutput对象的默认toString()方法,没有重写该方法的情况下,默认返回「类全限定名@哈希码」的格式,因此看不到内部属性内容。
解决方法
可根据使用场景选择以下任意方案:
方案1:JSP层嵌套遍历(无需修改后端代码)
在原有循环内部再加一层<c:forEach>遍历diffOutputList,直接读取每个DiffOutput对象的属性即可,示例如下(替换为你DiffOutput类的实际属性名):
<c:forEach items="${results.diffResponses}" var="diffResponse"> var distributionPath = '<c:out value="${diffResponse.distributionPath}"/>' console.log("Dist: ",distributionPath); // 初始化JS数组存储结果 const diffOutputList = []; <c:forEach items="${diffResponse.diffOutputList}" var="output"> // 此处替换为DiffOutput类对应的getter属性名 diffOutputList.push({ diffType: '<c:out value="${output.diffType}"/>', oldValue: '<c:out value="${output.oldValue}"/>', newValue: '<c:out value="${output.newValue}"/>' }); </c:forEach> console.log(diffOutputList); </c:forEach>
方案2:重写DiffOutput的toString()方法(适合调试场景)
如果仅需要打印查看内部属性,直接在DiffOutput类中重写toString()方法即可,IDE一般支持自动生成该方法,示例代码:
@Override public String toString() { return "DiffOutput{" + "diffType='" + diffType + '\'' + ", oldValue='" + oldValue + '\'' + ", newValue='" + newValue + '\'' + '}'; }
重写后你原有直接打印diffOutputList的代码即可正常输出属性内容。
方案3:后端序列化为JSON(适合复杂JS操作场景)
如果后续需要在JS中对该列表做大量操作,可以在后端提前把diffOutputList序列化为JSON字符串,JSP直接读取后转成JS对象即可:
- 后端
DiffResponse类扩展存储JSON的字段:
// 新增字段 private String diffOutputJson; // 赋值时序列化(以Jackson为例,也可使用Gson等工具) this.diffOutputJson = new ObjectMapper().writeValueAsString(diffOutputList);
- JSP读取代码:
const diffOutputList = JSON.parse('<c:out value="${diffResponse.diffOutputJson}" escapeXml="false"/>'); console.log(diffOutputList);
内容的提问来源于stack exchange,提问作者Thiluxan
相关产品推荐
相关产品推荐

