1

Spring MVC 3.0.1 フレームワークで String を Object に変換する際にいくつかの問題があります。カスタム Web エディターを使用してフォームから PostgreSQL データベースにデータを追加 (新しい製品を追加) したい場合、エラーは表示されず、フォーム フィールドがデータベースに挿入され、追加した製品の製品カテゴリのみが挿入されません (category_typesいくつかのカテゴリを挿入したところ、それらがビューに表示されます)。コントローラーで InitBinder メソッドを削除すると、必要なものを変換するエディターがないというエラーが表示されます。

これが私のカスタム Webeditor のコードです。

package Webeditors;
import java.beans.PropertyEditorSupport;
import Models.CategoryType;
public class CategoryTypeWebEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) throws IllegalArgumentException { 

    CategoryType a = new CategoryType(); 
    a.setId(Long.parseLong(text));
    setValue(a);  
}      

@Override
public String getAsText() {

    CategoryType type = (CategoryType) getValue();
    return type == null ? null :  Long.toString(type.getId());  
}      

}

私のCategoryTypeクラスは次のとおりです。

package Models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="category_types")
public class CategoryType {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY) 
long id;

String name;

public CategoryType(){}

public CategoryType(long id, String name){

    this.id = id;
    this.name = name;

}

...

@Override
public boolean equals(Object obj) {
    if(obj instanceof CategoryType){
        CategoryType a = (CategoryType)obj;
    return a.getId() == id;
    }
    return false;
}   
}

私の JavaBeans製品では、次のように宣言しました。

@ManyToMany(fetch=FetchType.EAGER)
List<CategoryType> type;

public Product(){

    type = new ArrayList<CategoryType>();

}
...

public List<CategoryType> getType() {
    return type;
}

public void setType(List<CategoryType> type) {
    this.type = type;
}

私のコントローラーには、次のようなものがあります。

@RequestMapping(method = RequestMethod.POST)

public String addProduct(Model model,
        @ModelAttribute("addproduct") Product product, BindingResult result){

....
}
@ModelAttribute("categorytypes")
public List<CategoryType> loadCategoryTypes() {
    List<CategoryType> types = dao.getCategory_Types();
    return types;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(CategoryType.class, new CategoryTypeWebEditor());
}

そして、私はそれを次のように表示しています:

<form:form cssClass="form-horizontal" method="Post"
        action="addproductform.html" commandName="addproduct">
<form:checkboxes items="${categorytypes}" path="type" itemValue="id" itemLabel="name" delimiter="<br>"/>
<form:errors cssStyle="margin-top: 10px; margin-left: 160px;" cssClass="alert alert-error" element="div" path="type" />
</form:form>

私はそれに固執したので、それが追加されていないという間違ったことをしています..ありがとう

4

0 に答える 0