在验证之前将值添加到请求对象中

时间:2016-10-15 22:33:03

标签: 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.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请求中获取此值(userName),我是通过令牌从oAuth服务获得的。 是否可以从@ControllerAdvice发送userName到验证约束?

@InitBinder
    public void dataBinding(WebDataBinder binder, HttpServletRequest req) {

        // userName
        req.getUserPrincipal().getName();
    }

感谢。

1 个答案:

答案 0 :(得分:0)

我找到了决定

@ControllerAdvice
public class GlobalControllerAdvice {


    @InitBinder
    public void dataBinding(WebDataBinder binder, HttpServletRequest request) {

        binder.bind(new MutablePropertyValues(Collections.singletonMap("userName",request.getUserPrincipal().getName())));
    }

}