【问题标题】:Spring Request Mapping post vs put, same method, same logic, butSpring Request Mapping post vs put,相同的方法,相同的逻辑,但是
【发布时间】:2018-02-20 22:25:17
【问题描述】:

我有两种方法: 第一个创建产品:

@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> create(@Validated ProductDTO productDTO){
        productService.addProduct(productDTO);
        return new ResponseEntity<>("Maxsulot ro'yhatga qo'shildi", HttpStatus.OK);
    }

另一个更新产品:

@RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<?> update(@Validated ProductDTO productDTO){
        productService.update(productDTO);
        return new ResponseEntity<>("Maxsulot ma'lumotlari yangilandi", HttpStatus.OK);
    }

现在,我很惊讶,如果我发送相同的数据 post 方法工作正常(screen1),但 put(screen2) 方法返回验证错误。 屏幕1(帖子)

screen2(放置)

问题是什么? MyDTO 类:

public class ProductDTO {

    private Long id;

    private MultipartFile file;

    @NotNull
    @Size(min = 2, max = 50)
    private String productName;

    @NotNull
    private Long productPrice;

    private String productInfo;

    @NotNull
    private Long categoryId;

    private String unitOfMeasurement;

    // getters and setters
}

【问题讨论】:

  • 什么是魔法,伙计? :)
  • 您能将您的应用程序写入控制台的内容发布出来吗?您可以看到有一些 BindException,从这条消息中您可能能够确定它来自哪里。
  • 你能分享你的DTO对象的代码吗?你有任何 initBinders 吗?
  • 我添加了 Mydto 类
  • 你在使用 Spring Boot 吗?如果不确定,请确保将 HttpPutFormContentFilter 添加到您的过滤器列表中。

标签: spring rest post spring-boot put


【解决方案1】:

我可以看到您有 @Validated 应该根据 JSR-303 验证您的请求正文。

POSTPUT 似乎不一致。它验证/不验证并返回错误,因为您的正文与您在 ProductDTO 上放置的验证规则不匹配。

在我看到的所有文档中,您应该做类似@Valid @RequestBody 之类的操作,而不是仅仅输入@Validated

尝试将其更改为上述内容,看看它现在是否可以更一致地工作。

【讨论】:

  • 如果我将 @Validated 更改为 @Valid @RequestBody,服务器无法解析 Multipart 文件。出现此错误:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
  • 哇,Put 方法返回错误#415,不支持的 MediaType :-)
  • 这是一个不同的问题,看看这个帖子:linklink
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
相关资源
最近更新 更多