验证前将值添加到请求对象中 [英] Add value into request object before validation
本文介绍了验证前将值添加到请求对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用@Restcontroller和@Vaid注释.
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;
....
}
我没有从传入的json请求中获取此值(用户名),我是通过令牌从oAuth服务获得的. 是否可以通过@ControllerAdvice将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();
}
谢谢.
推荐答案
我找到了决定
@ControllerAdvice
public class GlobalControllerAdvice {
@InitBinder
public void dataBinding(WebDataBinder binder, HttpServletRequest request) {
binder.bind(new MutablePropertyValues(Collections.singletonMap("userName",request.getUserPrincipal().getName())));
}
}
这篇关于验证前将值添加到请求对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文