2014-12-02 47 views
0

春季表单绑定面临的问题。我有两个模型分类和产品。春季表单绑定下拉对象

@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

你应该在你的控制器的动作如下变化:

for(Category category : categories) 
{ 
    categoriesMap.put(category.geCategorytId(), category.getCategoryName()); 
} 

,并在您的视图改变:

<form:select path="category.categoryID" > 

的选择下拉将有类别名称作为显示文字和类别ID作为值。

+0

感谢您的答复,但没有成功投用消息犯错未能类型的属性值“java.lang.String中”所需类型“长转换'for property'category.categoryID'; – Rohit 2014-12-02 11:39:25

0

这对我有效!

<form:select path="category.categoryID" > 
<form:options items="${categoryList}" itemValue="categoryID" /> 
</form:select> 
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>