我有一个带有UserStateDTO请求正文的POST端点。Junit测试工作正常;但是,由于“缺少必需的请求正文”,因此无法在浏览器中运行。如您所见,那里有尸体……这使我发疯。请在下面找到错误和摘要。
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void .....UserRestController.setState(UserStateDTO)
@PostMapping(value = "/state", consumes = MediaType.APPLICATION_JSON_VALUE)
public void setState(@RequestBody UserStateDTO userStateDTO) {
if (userStateDTO != UserStateDTO.ACTIVE && userStateDTO != UserStateDTO.DISABLED) {
throw new BusinessException(GeneralErrors.INVALID_REQUEST);
}
UserDTO userDTO = userService.getUser();
userDTO.setState(userStateDTO);
userService.updateUser(userDTO);
}
public enum UserStateDTO {
ACTIVE("ACTIVE"),
DISABLED("DISABLED");
private final String state;
private static final Map<String, UserStateDTO> states = new HashMap<>();
UserStateDTO(String state) {
this.state = state;
}
static {
for (UserStateDTO u : UserStateDTO.values()) {
states.put(u.getValue(), u);
}
}
@JsonValue
public String getValue() {
return state;
}
@JsonCreator
public static UserStateDTO fromValue(String state) {
return states.get(StringUtils.upperCase(state));
}
}
fetch("http://localhost:4200/user/state", {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en,hu;q=0.9,nb;q=0.8",
"content-type": "application/json",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-xsrf-token": "-"
},
"referrer": "http://localhost:4200/",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "{\"state\":\"ACTIVE\"}",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
您必须getState()
在枚举中添加方法。正确的代码如下:
public enum UserStateDTO {
ACTIVE("ACTIVE"),
DISABLED("DISABLED");
private final String state;
private static final Map<String, UserStateDTO> states = new HashMap<>();
UserStateDTO (String state) {
this.state = state;
}
static {
for (UserStateDTO u : UserStateDTO.values()) {
states.put(u.getValue(), u);
}
}
public String getState() {
return state;
}
@JsonValue
public String getValue() {
return state;
}
@JsonCreator
public static UserStateDTO fromValue(String state) {
return states.get(StringUtils.upperCase(state));
}
}
或者,您可以仅在方法内部添加fromValue()
注解@JsonProperty("state")
,该注解绑定您的请求正文值而不使用getter。正确的方法如下:
@JsonCreator
public static UserStateDTO fromValue(@JsonProperty("state") String state) {
return states.get(StringUtils.upperCase(state));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句