Spring MVC:POST和PUT无法正常工作

时间:2015-12-23 10:39:52

标签: java spring-mvc post put

我正在开发Spring MVC 4 Dynamic 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);
}

发布请求:

{
    "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上读到了我需要添加多部分重新配置器,但是后来又添加了我得到同样的错误。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

添加@ResponseBody将适用于此问题