简体   繁体   English

Spring controller 可以接受 ZonedDatedTime 作为@RequestParam 但不能接受@RequestBody

[英]Spring controller can accept ZonedDatedTime as @RequestParam but not @RequestBody

The following code works以下代码有效

public @ResponseBody
Map<String, Object> test(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime startDate,
                                       @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime endDate) {

    return null;
}

with this request有了这个要求

https://localhost:8080/api/v1/test?startDate=2000-10-31T01:30:00.000-00:00&endDate=2000-10-31T01:30:00.000-00:00

But the following code throws exception但是下面的代码抛出异常

public @ResponseBody
Map<String, Object> test(@RequestBody @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime startDate,
                                       @RequestBody @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime endDate) {

    return null;
}

with this body用这个身体

 {
    "endDate":"2000-10-31T01:30:00.000-00:00",
    "startDate":"2000-10-31T01:30:00.000-00:00"    
}

has this exception有这个例外

[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.ZonedDateTime value; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.ZonedDateTime value

You must use @ModelAttribute or make object or map for mapping body, because Reflection utils not have opportunity for reading function parameter names (you cant specify property name for mapping).您必须使用@ModelAttribute或制作 object 或 map 作为映射主体,因为反射实用程序没有机会读取 function 参数名称(您无法为映射指定属性名称)。

public class User {
    private String name;
    private String occupation;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@RestController
public class MyController {
    @ResponseStatus(value = HttpStatus.OK)
    @PostMapping(value="/myfoo")
    public void process2(@ModelAttribute("email") String email) {
    }

    @ResponseStatus(value = HttpStatus.OK)
    @PostMapping(value="/vals")
    public void process(@RequestBody MultiValueMap<String, String> values) {
    }

    @ResponseStatus(value = HttpStatus.OK)
    @PostMapping(value="/user", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void process2(@RequestBody User user) {
    }
}

ATTENTION注意力
always set name of property for @RequestParam , else you can take error if somebody add not only this parameter or changed function signature始终为@RequestParam设置属性名称,否则如果有人不仅添加此参数或更改 function 签名,您可能会出错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM