我有pojo:

public class Address {
    private String country;
    private String city;
    private String street;
    private String building;
    private String room;


和控制器的方法:

@RequestMapping(value = "/test_get_corporate_footprint", method = RequestMethod.GET)
public void getCorporateFootprint(@RequestParam("officeLocation") String officeLocation) {
    System.out.println(officeLocation); //{"country":"Belarus","city":"Minsk","street":"Bahdanovicha","building":"1/3v","room":"3"}
}


但是,当我更改控制器方法以接受Address作为参数时,它返回null:

@RequestMapping(value = "/test_get_corporate_footprint", method = RequestMethod.GET)
public void getCorporateFootprint(@RequestParam("officeLocation") Address officeLocation) {
    System.out.println(officeLocation);//null
}


怎么了?

"Failed to convert value of type 'java.lang.String' to required type 'com.model.Address'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.model.Address': no matching editors or conversion strategy found"

最佳答案

您不能将复杂类型(作为地址对象)映射到requestParameters(即http:/ localhost?param1 = 1&param2 = 2),而无需添加用于处理它们的自定义逻辑。

Spring通过使用自定义参数解析器从请求参数中预填充某种对象类型(例如HandlerMethodArgumentResolver)来做到这一点。

另外,在服务器上发出HTTP GET请求时,您不能传递正文/内容,因此,更灵活的解决方案是使用HTTP POST方法,将对象表示为JSON。

要利用此功能,可以在方法参数上使用@RequestBody批注。

因此,为使您的控制器方法能够接收到地址对象,您应该添加以下更改:

@RequestMapping(value = "/test_get_corporate_footprint", method = RequestMethod.POST)
public void getCorporateFootprint(@RequestBody Address officeLocation) {
    System.out.println(officeLocation);
}


另外,请确保在类路径中具有Jackson库。

然后,您可以使用发送发布请求

curl -X POST -H "Content-Type:application/json" -d '{"country":"someCountry","city":"city"}' http://server/test_get_corporate_footprint

10-05 18:06
查看更多