当一个字段不是字符串而是另一个对象时,如何使用Spring MVC提交表单? [英] How to submit a form with Spring MVC when one of the field is not a String but another object?
问题描述
这里是jsp.file的简化代码
My application is basically a dictionary. When I click on "submit" a new Word object is saved to the DB with its several fields. One of the field is called Category and it shows to which group the Word belongs. Currently this value is a String field of the Word object.
here is the simplified code for the jsp.file
以下是Word对象。
<form:form method="post" action="addNewWord.html" commandName="word" >
<table>
//many other fields;
<tr>
<td>Category:</td>
<td><form:select path="category" items="${CATEGORIES}"
var="cat">
</form:select></td>
<td><form:errors path="category" cssClass="error" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add new word" /></td>
</tr>
</table>
</form:form>
Here is the Word object.
在这种情况下,一切都很好,工作得很好, Word对象被保存到数据库。
但是,如果我决定创建一个独立的Category对象,并且Word对象中的类别字段不是字符串,而是类别的实例?
@Entity
@Table(name = "word")
public class Word {
//other instance variables either primitives or Strings;
@Column(name = "category", nullable = false, length = 80)
private String category;
//getters-setters
in this case everything is fine and works very well and the Word object gets saved to the database.
But what if I decided to create a standalone Category object and the category field in the Word object is not a String but an instance of the Category?
如何修改.jsp文件上的表单以提交包含字段的单词对象不是一个字符串,而是一个类别?
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
How should I modify the form on the .jsp file to submit the word object that has a field that is not a String but a category? Just for the whole picture let me show the method in the Controller that gets called by the submit:
我有一种感觉,我应该使用@InitBinder方法,但我不知道如何,这更像是一种感觉,而不是坚如磐石的事实。任何建议是受欢迎的。
@RequestMapping(value = "/addNewWord", method = RequestMethod.POST)
public String addNewWord(@ModelAttribute Word word, BindingResult result, Model model) {
WordValidator validator = new WordValidator();
validator.validateWord(word, result, wordService.getAllWord(), categoryService.getAllCategories());
if (!result.hasErrors()) {
wordService.save(word);
word.clearValues();
}
fillCategoryNames(model);
return "addNew";
}
推荐答案
在这里你可以:
Here you go :
和
and
有更多信息:
...
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Category.class, new CategoryEditor());
}
...
}
Spring 3
- Customizing WebDataBinder initialization (Spring doc)
- Spring 3 Type Conversion (Spring doc)
这篇关于当一个字段不是字符串而是另一个对象时,如何使用Spring MVC提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!