问题
I'm using @Restcontroller and @Vaid annotation.
@RequestMapping(path = "/1050"
method = RequestMethod.POST,
headers = {"Content-Type=application/json"},
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public UserListResp getUserList(@RequestBody @Valid UserListReq request, BindingResult bindingResult,
Principal principal){
UserListResp response = new UserListResp();
if (bindingResult.hasErrors()){
response.setResultCode(102); // Validation error
response.setErrMsg("Wrong " + bindingResult.getFieldError().getDefaultMessage() + " value.");
} else {
return userService.getUserList(request) ;
}
return response;
}
Incoming request mapped to object which validated.
public class UserListReq {
private String userName;
....
}
I'm not getting this value (userName) from incoming json request, I've got from oAuth service by token. Is it possible to send userName to validation constraint from @ControllerAdvice ?
@InitBinder
public void dataBinding(WebDataBinder binder, HttpServletRequest req) {
// userName
req.getUserPrincipal().getName();
}
Thanks.
回答1:
I've found decision
@ControllerAdvice
public class GlobalControllerAdvice {
@InitBinder
public void dataBinding(WebDataBinder binder, HttpServletRequest request) {
binder.bind(new MutablePropertyValues(Collections.singletonMap("userName",request.getUserPrincipal().getName())));
}
}
来源:https://stackoverflow.com/questions/40064924/add-value-into-request-object-before-validation