【问题标题】:Spring MVC controller ignores "consumes" propertySpring MVC 控制器忽略“消耗”属性
【发布时间】:2014-10-04 00:47:55
【问题描述】:

我有下面的控制器:

@RestController
@RequestMapping(value = "/v1/mail", consumes = {APPLICATION_JSON_VALUE})
@ResponseStatus(OK)
public class MailController {

    private CoreOutRestAdapter coreAdapter;

    @Autowired
    public MailController(CoreOutRestAdapter coreAdapter) {
        this.coreAdapter = coreAdapter;
    }

    @RequestMapping(method = POST)
    public void sendMail(@RequestBody @Validated Mail mail) {
        coreAdapter.sendMail(mail);
    }

}

和 classpath 中的 jackson-databind 2.3.2。但是如果我使用 Content-Type: application/json 发送 POST 请求,返回的响应包含 415 状态(不支持的媒体类型)。我不明白为什么控制器会忽略 @RequestMapping 注释中的“consumes”属性。我怎样才能解决这个问题?此外,您可以在 github https://github.com/f1xmAn/scail 找到项目的其余部分

【问题讨论】:

  • APPLICATION_JSON_VALUE 中的值是多少?您可以尝试将其移至方法级别。
  • @Keerthivasan 它是 org.springframework.http.MediaType.APPLICATION_JSON_VALUE ("application/json")。我试过了,但没有任何改变。顺便说一句,它必须适用于类级别。
  • 也许可以尝试从 sendMail 方法中将 consumes = {APPLICATION_JSON_VALUE} 添加到 @RequestMapping
  • @ArekWoźniak 返回相同的状态

标签: java json spring spring-mvc jackson


【解决方案1】:

我忘了用@EnableWebMvc 注释配置。注释控制器后工作正常。

【讨论】:

    【解决方案2】:

    以下是我的应用程序代码中的工作示例。

    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/abc")
    public class ABC {
    
    
        @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        @ResponseBody
        public String getRequest(@RequestBody XYZ xyz) {
    
            return "success";
       }
    

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2021-08-26
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2011-05-22
      • 2016-06-26
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多