【问题标题】:How do you force Spring MVC4 REST webservices to only accept parameters in json format?你如何强制 Spring MVC4 REST webservices 只接受 json 格式的参数?
【发布时间】:2016-03-06 22:58:38
【问题描述】:

有没有办法强制 Spring MVC4 REST webservices 接受某些格式的参数或请求?我希望我的 web 服务通过仅将参数附加到 url 端点来接受 JSON 参数。我尝试了下面的示例,但是您可以通过 url 传递一个参数,我希望他们以干净的 json 格式传递它我如何在春季执行此操作。

 @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@PathVariable("id") long id) {
    System.out.println("Fetching User with id " + id);
    User user = userService.findById(id);
    if (user == null) {
        System.out.println("User with id " + id + " not found");
        return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<User>(user, HttpStatus.OK);
}

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-restcontroller


    【解决方案1】:
    @RequestMapping(value = "/user/{id}", 
            method = RequestMethod.GET, 
            produces = MediaType.APPLICATION_JSON_VALUE, 
            consumes = MediaType.APPLICATION_JSON_VALUE)
    

    【讨论】:

      【解决方案2】:
       @RequestMapping(...,consumes= MediaType.APPLICATION_JSON_VALUE)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 2012-03-09
        • 2015-10-23
        • 1970-01-01
        • 2022-08-22
        • 2022-12-05
        • 1970-01-01
        相关资源
        最近更新 更多