Add value into request object before validation

浪尽此生 提交于 2019-12-11 04:14:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!