StuartZzzzzzzzzz 2019-12-22 19:01 采纳率: 0%
浏览 316

springboot绑定数据错误,希望大牛帮帮小白

在使用springboot从前端绑定数据的时候,出现如下错误

图片如下

图片说明

内容如下:

There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='mainCategory'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'mainCategory' on field 'subCategories': rejected value [[SubCategory{id=1, name='课后作业'}, SubCategory{id=2, name='实验报告'}, SubCategory{id=3, name='课堂课件'}]]; codes [typeMismatch.mainCategory.subCategories,typeMismatch.subCategories,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [mainCategory.subCategories,subCategories]; arguments []; default message [subCategories]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'subCategories'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.zjq.hbut.csdn.entity.SubCategory' for property 'subCategories[0]': no matching editors or conversion strategy found]

前端代码如下

<form action="" class="ui form" th:object="${mainCategory}" th:action="*{id}==null ? @{/admin/type/add}:@{/admin/type/add/{id}(id=*{id})}" method="post">

            <input type="hidden" name="id" th:value="*{id}">
            <input type="hidden" name="subCategories" th:value="*{subCategories}">
            <div class="required field">
                <div class="ui left labeled input">
                    <label class="ui teal basic label">名称</label>
                    <input type="text" name="name" placeholder="名称..." th:value="*{name}">
                </div>
            </div>
            <div class="ui right aligned container">
                <!--onclick事件返回上一个页面-->
                <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button>
                <button class="ui teal submit button">提交</button>
            </div>
        </form>

后端Controller代码如下

@PostMapping({"/type/add","/type/add/{id}"})
    public String add(@Valid MainCategory mainCategory, BindingResult result,
                      @PathVariable(name = "id",required = false)Long id,
                      @RequestParam(name = "subCategories") String subCategories,
                      RedirectAttributes attributes)
    {

        if(imainCategoryService.getByName(mainCategory.getName())!=null)
        {
            result.rejectValue("name","nameError","该标签已存在");
        }
        if(result.hasErrors())
        {
            System.out.println(result.getAllErrors());
            return "admin/type-input";
        }

        if(id!=null&&id>0)
        {//修改
            MainCategory update = imainCategoryService.update(mainCategory);
            if(update==null)
            {
                attributes.addFlashAttribute("message","更新成功");
            }else {
                attributes.addFlashAttribute("message","更新失败");
            }
            return "redirect:/admin/type";
        }else {
            //新增
            MainCategory save = imainCategoryService.save(mainCategory);
            if(save==null)
            {
                attributes.addFlashAttribute("message","保存成功");
            }else {
                attributes.addFlashAttribute("message","保存失败");
            }
            return "redirect:/admin/type";
        }
    }

实体类代码如下

package com.zjq.hbut.csdn.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "t_maincategory")
public class MainCategory {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToMany
    private List<SubCategory> subCategories=new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<SubCategory> getSubCategories() {
        return subCategories;
    }

    public void setSubCategories(List<SubCategory> subCategories) {
        this.subCategories = subCategories;
    }

    @Override
    public String toString() {
        return "MainCategory{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", subCategories=" + subCategories +
                '}';
    }
}

  • 写回答

1条回答 默认 最新

  • lshen01 2023-03-17 10:07
    关注

    参考GPT和自己的思路:

    根据你提供的错误信息和代码,问题应该出在前端的表单中。在表单中,第4行中的隐藏输入域subCategories绑定了实体类MainCategory中的subCategories属性。但是根据错误信息,这个属性的值被转换成了字符串类型,而在后台Controller中,这个属性被声明为了List类型,因此出现了类型转换错误。

    解决方法可以考虑以下两个方案:

    1. 在前端表单中将subCategories属性的值转换为正确的类型,即List类型。可以使用JavaScript来将字符串形式的值转换为List类型。

    2. 在后台Controller中,修改subCategories属性的类型为String,然后手动将字符串形式的值转换为List类型。可以在Controller中增加一些转换代码,通过自定义转换器或者手动转换将字符串转换为List类型。

    需要注意的是,在处理表单数据时,一定要保证表单中的数据类型和后台处理数据时的数据类型保持一致。这样才能避免类型转换错误,从而保证数据的正确性。

    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备