【问题标题】:Add value into request object before validation在验证之前将值添加到请求对象中
【发布时间】:2017-02-25 04:05:20
【问题描述】:

我正在使用@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 请求中获取此值(用户名),而是通过令牌从 oAuth 服务中获取的。 是否可以从 @ControllerAdvice 将 userName 发送到验证约束?

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

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

谢谢。

【问题讨论】:

标签: spring-mvc bean-validation spring-validator


【解决方案1】:

我找到了决定

@ControllerAdvice
public class GlobalControllerAdvice {


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

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2014-05-25
    • 2020-07-13
    • 2019-09-30
    • 2019-07-08
    相关资源
    最近更新 更多