【问题标题】:Spring MVC : POST and PUT not workingSpring MVC:POST和PUT不起作用
【发布时间】:2015-12-23 21:08:11
【问题描述】:

我正在开发 Spring MVC 4 动态 web 模块应用程序。 在我的应用程序中,我有简单的 CRUD 操作。 获取请求工作正常,但 POST 和 PUT 根本不工作。 我收到此错误:
HTTP 状态 400 - 客户端发送的请求在语法上不正确。

这是我的 GET 控制器代码:

@RequestMapping(value = "/getCustomreById/{id}", method = RequestMethod.GET)
    public ResponseEntity<CustomerDetails> getCustomer(
            @PathVariable("id") String id) {
        System.out.println(id);
        if (id != null)
            return new ResponseEntity<CustomerDetails>(
                    serv.getCustomerById(id), HttpStatus.OK);
        else
            return new ResponseEntity<CustomerDetails>(
                    serv.getCustomerById("1"), HttpStatus.OK);
    }

对于POST

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public int AddCustomer(@RequestBody CustomerDetails customer) {
    return serv.addCustomer(customer);
}

POST 请求:

{
    "customerName": "Sid",
    "customerEmail": "sid@gmail.com",
    "customerAddress": [{    
        "address1": "123 Street",
        "address2": " ",
        "zipCode": "400065",
        "city": "Mumbai",
        "state": "Maharashtra",
        "country": "India",
        "region": "Gateway of India"
    }]
}  

我在 this 上的 stackoverflow 上阅读了我需要添加多部分解析器的问题,但即使在添加后我也遇到了同样的错误。

【问题讨论】:

  • 请求的uri/url是什么?
  • 您是如何发送请求的。这段代码的客户端是什么?
  • @SheetalMohanSharma Uri : localhost:8082/WebApp/customer/addCustomer 目前还没有客户端代码,我正在 Rest Client for firfox 上对其进行测试。@VivekSingh
  • @RushikeshKhamborkar 这个答案有帮助吗?
  • 请求的 Content-Type 标头是什么?您还可以发布类 CustomerDetailsCustomerAddress

标签: java spring-mvc post put


【解决方案1】:

假设您只需要发送int id 作为响应,请将@ResponseBody 添加到方法中

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
@ResponseBody
public int AddCustomer(@RequestBody CustomerDetails customer) {
    return serv.addCustomer(customer);
}

否则返回ResponseEntity,就像你对GET所做的那样

return new ResponseEntity<Integer>(serv.addCustomer(customer), HttpStatus.OK);

【讨论】:

  • 这篇文章没有回答问题。
  • 你为什么这么认为?
  • 他收到的问题是HTTP Status 400 - The request sent by the client was syntactically incorrect. 这与客户端请求资源的方式有关。
  • 尝试在没有@ResponseBody的情况下实现问题中提到的代码,您将能够重现该问题
【解决方案2】:

添加@ResponseBody 可以解决这个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 2017-07-28
    • 2019-10-23
    • 2019-05-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    相关资源
    最近更新 更多