在表单中绑定数据期间出现BindException

时间:2018-01-04 13:36:29

标签: java spring thymeleaf

控制器看起来像这样:

@RequestMapping("/product/new")
public String newProduct(Model model) {
    model.addAttribute("cat", categoryService.getAllCategoriesCommand());
    model.addAttribute("productf", new ProductCommand());
    return "product/addProduct";
}

 @PostMapping("product")
public String saveNewProduct(@ModelAttribute("productf") ProductCommand productCommand, Model model) {
    productService.saveCommand(productCommand);
    return "redirect:/index";
}

表格:

      <tr th:each="category : ${cat}">
        <div class="radio">
            <label>
                <input type="checkbox" value="" th:value="${category.id}" th:text="${category.categoryName}" th:field="*{categories}"/>
            </label>
        </div>

域/命令类:

@Entity
@EqualsAndHashCode(exclude = "categories")
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private BigDecimal price;
private String manufacturer;
private Long unitsInStock;
private boolean discontinued;
private Byte[] image;

//@ElementCollection
//private Map<String, String> productProperties = new HashMap<>();

@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "product_category",
        joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private Set<Category> categories = new HashSet<>();
}

ProductCommand类:

@NoArgsConstructor
public class ProductCommand {

private Long id;
private String name;
private String description;
private BigDecimal price;
private String manufacturer;
private Long unitsInStock;
private boolean discontinued;
private Byte[] image;
private Set<CategoryCommand> categories = new HashSet<>();
}

分类:

@Entity
@EqualsAndHashCode(exclude = "products")
public class Category  {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String categoryName;

@ManyToMany(mappedBy = "categories")
private Set<Product> products; 
}

CategoryCommand类:

@NoArgsConstructor
public class CategoryCommand {

private Long id;
private String categoryName;
}

当我想提交表单时,我收到以下错误:

Resolved exception caused by Handler execution: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'productf' on field 'categories': rejected value [1]; codes [typeMismatch.productf.categories,typeMismatch.categories,typeMismatch.java.util.Set,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productf.categories,categories]; arguments []; default message [categories]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Set' for property 'categories'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'info.mike.webstorev1.commands.CategoryCommand' for property 'categories[0]': no matching editors or conversion strategy found]

我不知道为什么Spring无法转换String,我看不到任何字符串。当我(在控制器中)传递给模型New Product和categoryService.getAllCategories()而不是New ProductCommand和categoryService.getAllCategoriesCommand()时,它都运行良好,没有例外。我正在寻求帮助。

编辑:

   @Transactional
@Override
public ProductCommand saveCommand(ProductCommand productCommand) {
    Product detachedProduct = productCommandToProduct.convert(productCommand);
    Product savedProduct = productRepository.save(detachedProduct);
    return productToProductCommand.convert(savedProduct);
}

1 个答案:

答案 0 :(得分:0)

您需要在活页夹上注册自定义编辑器,以便将String转换为Server实例。 Spring参考文档中有一个自定义PropertyEditor here的示例,可以帮助您入门。