【问题标题】:@RequestBody optional (e.g. required=false)@RequestBody 可选(例如 required=false)
【发布时间】:2012-03-15 14:15:54
【问题描述】:

有没有办法让 @RequestBody 注释选项(例如 required=false)像 RequestParam 一样支持?

我通过代码的主要路径是使用 POST。但是,出于调试目的,我还想通过浏览器基本 http 请求支持基本 GET 请求。但是,当我尝试这样做时,会收到 415 不支持的媒体错误。

【问题讨论】:

    标签: spring-mvc annotations


    【解决方案1】:

    我通过代码的主要路径是使用 POST。但是,我还想通过浏览器支持基本的 GET 请求

    为此,请使用@RequestMapping 注释的method 属性,例如

    @RequestMapping(value="/myPath", method=RequestMethod.GET)
    public String doSomething() {
       ...
    }
    
    @RequestMapping(value="/myPath", method=RequestMethod.POST)
    public String doSomething(@RequestBody payload) {
       ...
    }
    

    【讨论】:

    • 最快的修复方法。找不到我需要添加到 Spring 以更改默认行为的配置。我正在使用 Spring3.2,如果我发送 GET 请求会收到错误 415,这是最快的解决方案。
    【解决方案2】:

    @RequestBody 现在显然可以从 Spring 3.2M1 开始设置为可选:https://jira.springsource.org/browse/SPR-9239

    但是,我在 Spring 3.2M2 中对此进行了测试,即使在设置 required=false 之后,它也会在通过 null 正文发送时抛出异常,而不是通过 null。此问题已确认并已修复,计划 3.2 RC1

    【讨论】:

      【解决方案3】:

      有没有办法让 @RequestBody 注释选项(例如 required=false)像 RequestParam 一样支持?

      简而言之,我不这么认为, 但您可以从输入流中手动完成:

      @Autowired
      private MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter;
      
      RestResponse<String> updateViewingCard(@PathVariable(value = "custome") String customer,
              @RequestParam(value = "p1", required = false) String p1,
              @RequestParam(value = "p2", required = false) String p2, 
              // @RequestBody MyPayloadType payload,     Can't make this optional
              HttpServletRequest request,
              HttpServletResponse response)  throws... {
      
          MyPayloadType payload = null;
          if (0 < request.getContentLength()) {
                  payload = this.mappingJacksonHttpMessageConverter.getObjectMapper().readValue(request.getInputStream(),
                          MyPayloadType.class);
          }
      

      【讨论】:

        【解决方案4】:

        是的,你可以。在 Spring 4 或 Spring Boot 1.5 中,您可以通过以下方式进行操作:

        @PostMapping("/error-report")
        public String errorReport(@RequestBody(required = false) ErrorReportModel errorReportModel) {
        
            // YOUR LOGIC
        
            return "page-to-return";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-29
          • 1970-01-01
          • 1970-01-01
          • 2017-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多