Java Spring窗体绑定下拉对象
在spring表单绑定中面临问题。假设我有两个模型类别和产品Java Spring窗体绑定下拉对象,java,spring,spring-mvc,Java,Spring,Spring Mvc,在spring表单绑定中面临问题。假设我有两个模型类别和产品 @Entity @Table(name="PRODUCT") public class Product { @Id @GeneratedValue private long productID; @ManyToOne @JoinColumn(name="categoryID") private Category category; //Getters and setters } @Entity
@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;
}
@RequestMapping(value=“/productpage”,method=RequestMethod.GET)
私有模型和视图getAddProductPage(){
ModelAndView ModelAndView=新的ModelAndView(“添加产品”、“产品”、新产品());
Map categoriesMap=newhashmap();
List categories=categoryService.getAllCategories();
if(categories!=null&&!categories.isEmpty())
{
用于(类别:类别)
{
categoriesMap.put(category,category.getCategoryName());
}
}
addObject(“categoryList”,categories);
返回模型和视图;
}
我能够使用以下代码填充JSP页面中类别的下拉值:
<form:select path="category" >
<form:options items="${categoryList}"/>
</form:select>
提交表单时,我遇到错误400,客户端发送的请求语法不正确。未能将类型为“java.lang.String”的属性值转换为属性“Category”所需的类型“com.example.model.Category”。
如果我查看每个选项的页面源,则正确分配了类别。但我不明白为什么春天会犯这样的错误。。我需要帮助。提前谢谢 您应该对控制器的操作进行以下更改:
for(Category category : categories)
{
categoriesMap.put(category.geCategorytId(), category.getCategoryName());
}
在你看来,改变:
<form:select path="category.categoryID" >
“选择”下拉列表将类别名称作为显示文本,类别ID作为值。这对我来说很有效
<form:select path="category.categoryID" >
<form:options items="${categoryList}" itemValue="categoryID" />
</form:select>
${category.categoryName}
或
选择。。。
感谢您的响应,但它不起作用。错误提示消息无法将“java.lang.String”类型的属性值转换为属性“category.categoryID”所需的类型“long”;
<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>