在提交下面的表单是我的代码
后,我没有在spring控制器中获取表单数据@RequestMapping(value = "category/addCategory.htm" , method = RequestMethod.GET)
public String add(Model model) {
if (log.isDebugEnabled()){
log.debug("Invoking listCategory");
}
model.addAttribute("categoryView", new CategoryView());
return "editCategory";
}
@RequestMapping(value = "category/saveCategory.htm", method = RequestMethod.POST)
public String saveCategory(CategoryView categoryView, Model model, BindingResult result) {
Category category = prepareCategoryFromView(categoryView);
categoryService.save(category);
categoryView.setCategoryId(category.getCategoryId());
model.addAttribute("categoryView",categoryView);
return "editCategory";
}
prepareCategoryFromView是一个方法,它在Category it的hibernate实体上设置实际值,在categoryView
下面public class CategoryView {
private long categoryId;
private String image = "";
private int parentId;
private boolean top;
private int column = 1;
private int sortOrder = 1;
private boolean status;
private String description;
private String name;
.
.
other variable and setter and getters
}
,表格是
<sf:form method="post" enctype="multipart/form-data" id="form-category" cssClass="form-horizontal" modelAttribute="categoryView">
<sf:label path="name" cssClass="col-sm-2 control-label">Category Name</sf:label>
<sf:input path="name" id="name" name="name" cssClass="form-control" placeholder="Category Name" />
<sf:hidden path="categoryId" id="categoryId" name="categoryId" />
<sf:hidden path="languageId" id="languageId" name="languageId" />
<sf:label path="description" cssClass="col-sm-2 control-label">Category Name</sf:label>
<sf:textarea path="description" cssClass="form-control" placeholder="Description" id="description"/>
.
.
.
</sf:form>
每次我获取名称和描述时都是上述形式(我认为它创建了一个没有给定值的新视图对象)
请告诉我,我错了
答案 0 :(得分:3)
从enctype="multipart/form-data"
标记中删除form
,然后重试(使用正确顺序的方法参数)。由于您的属性名称与类名匹配,因此不严格要求@ModelAttribute
。
答案 1 :(得分:0)
我认为在CategoryView对象上缺少@ModelAttribute
注释。因为根据你的表单代码,它是模型属性,它将数据绑定到控制器中的bean。
使用下面的方法参数附加它,然后您可以检查数据是否绑定到它。
@RequestMapping(value = "category/saveCategory.htm", method = RequestMethod.POST)
public String saveCategory(@ModelAttribute("categoryView") CategoryView categoryView, Model model, BindingResult result) {
Category category = prepareCategoryFromView(categoryView);
categoryService.save(category);
categoryView.setCategoryId(category.getCategoryId());
model.addAttribute("categoryView",categoryView);
return "editCategory";
}