【问题标题】:Problem while posting data in spring boot Rest Api- org.springframework.web.bind.MethodArgumentNotValidException在 Spring Boot Rest Api-org.springframework.web.bind.MethodArgumentNotValidException 中发布数据时出现问题
【发布时间】:2020-08-07 10:05:43
【问题描述】:

我是 Spring Boot Rest API 的新手。 我创建了一个类别 Rest 控制器,使用它我将数据发布到我的后端 mysql 数据库。

我还在我的项目中添加了 spring-jpa 和 hibernate,它工作正常。 当我使用 Bootstrap 表单和 JqueryAjax 发布数据时,当我在表单中点击提交按钮时,我会在 intellij 控制台中获取 org.springframework.web.bind.MethodArgumentNotValidException 并在浏览器控制台中获取 400。

我的休息控制器代码

private CategoryRepository categoryRepository;

    //@GetMapping("/Categories")
    @RequestMapping(value="/Categories", method=RequestMethod.GET)
    public Page<Category> getAllCategories(Pageable pageable) {
        return categoryRepository.findAll(pageable);
    }


    //@PostMapping("/Categories")
    @RequestMapping(value="/Categories", method=RequestMethod.POST)
    public Category createCategory( @Valid @RequestBody Category Category) {
        return categoryRepository.save(Category);
    }

我的 js-ajax 文件

$(document).ready(
    function() {

        // SUBMIT FORM
        $("#Cateform").submit(function(event) {
            // Prevent the form from submitting via the browser.
            event.preventDefault();
            ajaxPost();
        });

        function ajaxPost() {
            // PREPARE FORM DATA
            var formData = {

                CategoryId : $("#CatId").val(),
                CategoryName : $("#CatName").val(),
                CategoryDescription : $("#Catdesc").val()
            }

            // DO POST
            $.ajax({
                type : "POST",
                contentType : "application/json",
                url : "http://localhost:8080/Categories",
                data : JSON.stringify(formData),
                dataType : 'json',
                success : function(result) {
                    if (result.status == "success") {
                        $("#postResultDiv").html(
                            "" + result.data.CategoryName
                               + result.data.CategoryDescription
                            + "Post Successfully! <br>"
                            + "---> Congrats !!" + "</p>");
                    } else {
                        $("#postResultDiv").html("<strong>Error</strong>");
                    }
                    console.log(result);
                },
                error : function(e) {
                    alert("Error!")
                    console.log("ERROR: ", e);
                }
            });

        }
    })

我的引导表单

<form id="Cateform">

        <div class="form-group">
            <input type="hidden" class="form-control" id="CatId" placeholder="Enter Book Id" name="CategoryId">
        </div>

        <div class="form-group">
            <label for="CatName">Category Name:</label>
            <input type="text" class="form-control" id="CatName"  name="CategoryName">
        </div>

        <div class="form-group">
            <label for="Catdesc">Category Desc:</label>
            <input type="text" class="form-control" id="Catdesc"  name="CategoryDescription">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

我的类别模型

@Entity
@Table(name = "Categories")
public class Category extends AuditingModel {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer categoryId;
    public String CategoryName;

    @NotNull
    @Size(max = 250)
    public String Description;


 //gettter and setters
}

好消息是...我能够使用 swagger-UI 和 PostMan 发布数据,但我不知道当我使用表单发布数据时发生了什么,并且获取方法参数对于我的描述字段无效类别模型。 我已在模型中将此字段设置为 notnull,但为什么它从 UI 而不是从 Swagger-UI 和 Postman 发布数据时给出错误。

以下是我在表单中点击提交时在 intellij 控制台中遇到的确切错误

** 已解决 [org.springframework.web.bind.MethodArgumentNotValidException:公共 edu.ait.shoppingCart.Dto.Category edu.ait.shoppingCart.Controllers.CategoryController.createCategory(edu.ait.shoppingCart.Dto.类别):[字段“描述”上的对象“类别”中的字段错误:拒绝值 [null];代码 [NotNull.category.Description,NotNull.Description,NotNull.java.lang.String,NotNull];参数 [org.springframework.context.support.DefaultMessageSourceResolvable:代码 [category.Description,Description];论据 [];默认消息[描述]];默认消息 [不能为空]] ] ** browser error

【问题讨论】:

    标签: spring-boot rest spring-restcontroller


    【解决方案1】:

    请注意,问题是变量名不匹配。 ajax 调用发送 CategoryDe​​scription 而实体期望 Description 还注意 categoryId 上区分大小写的 C。 Ajax 调用发送大写 C,而实体声明为小写字母 c

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 2021-11-29
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2020-09-27
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多