0
你可以有一個@Initbinder
在同一表單中的幾個數據?多個表單對象上的InitBinder
我有一個彈簧窗體,其中包含一個對象和兩個數據區的選擇下拉列表,我有一個Initbinder的日期,否則我得到一個提交錯誤。但我也需要將下拉列表綁定到一個對象。
我有一個類型,它有兩個日期和一個Category
,它是Category
我需要綁定,因爲它不能在保存時爲空。 我認爲這將幫助我驗證表單。 所以我可以在我的類型控制器中有這個嗎?
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
binder.registerCustomEditor(Category.class, "category", new CategoryEditor(CategoryService));
}
這是咋回事:
public class CategoryEditor extends PropertyEditorSupport {
private CategoryService categoryService;
public CategoryEditor(CategoryService categoryService) {
this.categoryService = categoryService;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text.equals("0")) {
this.setValue(null);
} else {
Category sc = categoryService.getCategory(Integer.parseInt(text));
this.setValue(sc);
}
}
@Override
public String getAsText() {
Category parent = new Category();
if (this.getValue() != null) {
parent = (Category) this.getValue();
}
return "";
}
}
我的JSP頁面
<s:url value="/mvc/type/save" var="actionUrl" />
<sf:form method="POST" modelAttribute="type" action="${actionUrl}">
<fieldset>
<legend><s:message code="${heading}" /></legend>
<table>
<tr>
<th><label for="category"><s:message code="category" />:</label></th>
<td><sf:select path="category.ID" id="category">
<sf:option value="0"> </sf:option>
<sf:options items="${listOfCategories}" itemLabel="name" itemValue="ID" />
</sf:select></td>
</tr>
<tr>
<th><label for="name"><s:message code="name" />:</label></th>
<td><sf:input path="name" id="name" />
<sf:hidden path="ID" />
<sf:hidden path="version" /></td>
</tr>
<tr>
<th><label for="marketing"><s:message code="marketing" />:</label></th>
<td><sf:input path="marketingFunction" id="marketing" /></td>
</tr>
<tr>
<th><label for="status"><s:message code="status" />:</label></th>
<td><sf:select path="lifeCycleStatus">
<sf:option value="0"> </sf:option>
<sf:options items="${listOfEnums}" />
</sf:select></td>
</tr>
<tr>
<th><label for="validfrom"><s:message code="validfrom" />:</label></th>
<td><sf:input path="validFrom" id="validfrom" /></td>
</tr>
<tr>
<th><label for="validuntil"><s:message code="validuntil" />:</label></th>
<td><sf:input path="validUntil" d="validuntil" /></td>
</tr>
<tr>
<td colspan="2">
<input id="saveButton" class="right" type="submit" title="<s:message code="save" />" value=" [ <s:message code="save" /> ] " />
</td>
</tr>
</table>
</fieldset>
</sf:form>
所以我的問題:我可以在我的控制器相同initBinder
多個粘合劑?這看起來像我不能,因爲我從來沒有輸入CategoryEditor
。我該怎麼做呢?
啊謝謝! :)現在我的編輯器被調用。 但是現在選擇了dropown中的最後一個元素,如果我查看源代碼,則下拉列表中的所有元素都將「selected = selected」。是否有可能只選擇頂層元素? – user2018311
你的'CategoryEditor'是有缺陷的。你的'getAsText'總是返回'''',而你可能應該返回id。 –
我想我使用path = category.ID,因爲我使用相同的表單來編輯Type。如果我不使用path = category.ID,當我選擇編輯一個類型時,類別不會被選中。所以現在不行了。 – user2018311