面对spring form binding中的问题。我有两个模型Category和Product。
@Entity
@Table(name="PRODUCT")
public class Product
{
@Id
@GeneratedValue
private long productID;
@ManyToOne
@JoinColumn(name="categoryID")
private Category category;
//Getters and setters
}
@Entity
@Table(name = "CATEGORY")
public class Category {
@Id
@GeneratedValue
private long categoryID;
private String categoryName;
}
在控制器中渲染添加产品页面
@RequestMapping(value = "/productpage", method=RequestMethod.GET)
private ModelAndView getAddProductPage(){
ModelAndView modelAndView = new ModelAndView("add-product","product",new Product());
Map<Category,String> categoriesMap = new HashMap<Category, String>();
List<Category> categories = categoryService.getAllCategories();
if(categories != null && !categories.isEmpty())
{
for(Category category : categories)
{
categoriesMap.put(category, category.getCategoryName());
}
}
modelAndView.addObject("categoryList",categories);
return modelAndView;
}
我可以使用以下代码填充JSP页面中类别的下拉值:
<form:select path="category" >
<form:options items="${categoryList}"/>
</form:select>
提交表单时我面临错误400客户端发送的请求在语法上是不正确的。Failed to convert property value of type 'java.lang.String' to required type 'com.example.model.Category' for property 'category'.
如果我查看每个选项类别的页面源正确分配。但不明白为什么春天投掷错误..需要帮助。提前谢谢!
答案 0 :(得分:1)
这对我有用!
<form:select path="category.categoryID" >
<form:options items="${categoryList}" itemValue="categoryID" />
</form:select>
答案 1 :(得分:0)
您应该在Controller的操作中进行以下更改:
for(Category category : categories)
{
categoriesMap.put(category.geCategorytId(), category.getCategoryName());
}
并在您的观点中更改:
<form:select path="category.categoryID" >
选择下拉列表将类别名称作为显示文本,类别ID作为值。
答案 2 :(得分:0)
<form:select path="category">
<c:forEach items="${categoryList}" var="category">
<form:option value="${category}">${category.categoryName}</form:option>
</c:forEach>
</form:select>
或
<form:select class="form-control" path="site">
<form:option value="-1">Select...</form:option>
<form:options items="${categoryList}" itemValue="categoryID" itemLabel="categoryName"/>
</form:select>