【发布时间】:2025-12-03 00:05:01
【问题描述】:
我有一个表,其中包含在 java 类的构造函数中设置的各种属性。我需要显示所有属性,但是当我想以简单的方式获得空指针时。我已经尝试过 jstl if 并且 jstl 选择这样做。
<c:choose>
<c:when test="${empty animal.getEarSize()}">
not set!
</c:when>
<c:otherwise>
${animal.getEarSize()}
</c:otherwise>
</c:choose>
但是当我尝试运行它时,我得到 HTTP 状态 500 - 处理 JSP 页面时发生异常。 animal 是 jstl for 循环中的变量,并非所有动物在构造函数中都有 earsize。
我在这里做错了什么? 是否有其他方法可以做到这一点,或者这是使用 jstl choose 或 if 做到这一点的唯一方法?
编辑:我在控制器中使用了一个方法,它给出了一个带有动物对象的地图,我正在循环通过。
public AfricanElephant(String color, String bodyCovering, String name, double weight, Gender gender, int earSize) {
super(color, bodyCovering, name, weight, gender, maxNumberOfEggs, earSize);
}
public Parrot(String color, String bodyCovering, String name, double weight, Gender gender) {
super(color, bodyCovering, name, weight, gender, maxNumberOfEggs);
}
这些是大象构造函数中的两个示例构造函数,有一个 earsize 变量,但在 parrot 构造函数中,没有 earsize 变量。
编辑:我已将选择更改为:
<td>
<c:if test="${animal.getClass().name eq 'myPackage.MyPath.AfricanElephant'}">${animal.earSize}</c:if>
这修复了 HTTP 状态 500 错误,但现在它在表格中显示 0 而不是我设置的 earsize。
我的控制器:
@Controller("animalController")
公共类 AnimalController {
ArrayList<Animal> animals = new ArrayList<Animal>();
@RequestMapping(value = "/animaloverview", method = RequestMethod.GET)
public String animals(Map<String, Object> model, @RequestParam(value = "race", required = false, defaultValue = "") String race){
if(race.isEmpty()){
model.put("animals", Zoo.getInstance().getAllAnimals());
}
else{
model.put("animals", Zoo.getInstance().getAnimalsByRace(race));
}
return "animalkingdom";
}
【问题讨论】: