这是我的 Controller 的相关代码:
@ModelAttribute("store_location_types")
public StoreLocationType[] getStoreLocationTypes() {
return StoreLocationType.values();
}
这是 StoreLocationType 的定义,在同一 Controller 中定义:
private enum StoreLocationType {
PHYSICAL("Physical"),
ONLINE("Online");
private String displayName;
private String value;
private StoreLocationType(String displayName) {
this.displayName = displayName;
this.value = this.name();
}
public String getDisplayName() {
return this.displayName;
}
public String getValue() {
return this.value;
}
}
以下是相关的 JSP 代码:
<li>
<label>Location Type:</label>
<form:radiobuttons path="StoreLocationType" items="${store_location_types}" itemLabel="displayName" itemValue="value"/>
</li>
以下是呈现页面时生成的内容:
<li>
<label>Location Type:</label>
<span>
<input id="StoreLocationType1" name="StoreLocationType" type="radio" value="">
<label for="StoreLocationType1">Physical</label>
</span>
<span>
<input id="StoreLocationType2" name="StoreLocationType" type="radio" value="">
<label for="StoreLocationType2">Online</label>
</span>
</li>
值属性没有填充我的枚举的“值”字段。我在这里做错了什么?我期望看到的是这样的:
<span>
<input id="StoreLocationType1" name="StoreLocationType" type="radio" value="PHYSICAL">
<label for="StoreLocationType1">Physical</label>
</span>
<span>
<input id="StoreLocationType2" name="StoreLocationType" type="radio" value="ONLINE">
<label for="StoreLocationType2">Online</label>
</span>
输入标签的value属性应该是StorLocationType.ONLINE.getValue()的值
最佳答案
我在您的代码中找不到任何问题。当我测试时效果很好。
但在这种情况下,你可以用更简单的方式来做到这一点。您不需要添加 value
枚举中的字段。如果省略 itemValue
<form:radiobuttons>
的属性Spring会将枚举实例的名称作为itemValue
的值属性。
所以你可以这样做。
枚举
private enum StoreLocationType {
PHYSICAL("Physical"),
ONLINE("Online");
private String displayName;
private StoreLocationType(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return this.displayName;
}
}
JSP
<label>Location Type:</label>
<form:radiobuttons path="StoreLocationType"
items="${store_location_types}" itemLabel="displayName" />
关于java - Spring MVC 表单 :radiobuttons tag not setting value attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17255519/