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
<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.
@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?
@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:
@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";
}
I have a feeling that I should use @InitBinder method but I do not know how, and it is more like a feeling than rock solid fact. Any advice is welcome.
Here you go :
and
Fore more information :