2012-09-15 32 views
1

我的應用程序基本上是一本字典。 當我點擊「提交」時,一個新的Word對象被保存到數據庫中,其中有幾個字段。其中一個字段被稱爲Category,它顯示Word屬於哪個組。目前這個值是Word對象的字符串字段。當一個字段不是字符串而是另一個對象時,如何使用Spring MVC提交表單?

這裏是用於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> 

這裏是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 

在這種情況下,一切都很好,工作得很好,Word對象被保存到數據庫。 但是,如果我決定創建獨立的類別對象,並且Word對象中的類別字段是而不是字符串,而是類別的實例呢?

@ManyToOne 
@JoinColumn(name = "category_id") 
private Category category; 

我應該怎樣修改的.jsp文件提交,有一個領域是不是一個字符串,但一個類別字對象的形式?只是整個畫面讓我給在被由被稱爲控制器的方法提交:

@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"; 
} 

我有,我應該使用@InitBinder方法的感覺,但我不知道怎麼了,它更像一種感覺比堅如磐石的事實。任何建議是受歡迎的。

回答

2

在這裏你去:

public class CategoryEditor extends PropertyEditorSupport { 

    // Converts a String to a Category (when submitting form) 
    @Override 
    public void setAsText(String text) { 
     Category c = new Category(); 
     c.setName(text); 
     this.setValue(c); 
    } 

    // Converts a Category to a String (when displaying form) 
    @Override 
    public String getAsText() { 
     Category c = (Category) this.getValue(); 
     return c.getName(); 
    } 

} 

... 
public class MyController { 

    @InitBinder 
    public void initBinder(WebDataBinder binder) { 
     binder.registerCustomEditor(Category.class, new CategoryEditor()); 
    } 

    ... 

} 

富勒更多信息:

+0

快速,可以理解,有用 –

相關問題