Spring mvc 在验证之前向请求对象添加值
我正在使用@Restcontroller和@Vaid注释Spring mvc 在验证之前向请求对象添加值,spring-mvc,bean-validation,spring-validator,Spring Mvc,Bean Validation,Spring Validator,我正在使用@Restcontroller和@Vaid注释 @RequestMapping(path = "/1050" method = RequestMethod.POST, headers = {"Content-Type=application/json"}, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.A
@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;
}
映射到已验证的对象的传入请求
public class UserListReq {
private String userName;
....
}
我不是从传入的json请求中获取这个值(用户名),而是通过令牌从oAuth服务中获取的。
是否可以从@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())));
}
}
我已经找到了决定
@ControllerAdvice
public class GlobalControllerAdvice {
@InitBinder
public void dataBinding(WebDataBinder binder, HttpServletRequest request) {
binder.bind(new MutablePropertyValues(Collections.singletonMap("userName",request.getUserPrincipal().getName())));
}
}
谢谢,但我的问题更难解决。我有rest控制器,我已经在body请求中发送了json(我没有使用POST或GET表单参数)。谢谢检查,但我的问题更难解决。我有rest控制器,并且在body请求中发送了json(我没有使用POST或GET表单参数)。