如果有可能为不同的控制器方法定制验证器,我想得到答案。
简单的验证器
@Component
public class UserDtoValidator implements Validator {
@Autowired
UserService userService;
@Override
public boolean supports(Class<?> aClass) {
return UserDto.class.isAssignableFrom(aClass);
}
@Override
public void validate(Object target, Errors errors) {
UserDto userDto = (UserDto) target;
}
//how to make 'if' below to be applied only for certain method in controller
//in this case for controller createUser method
if (userService.findByUserName(userDto.getUserName())!=null) {
throw new InvalidPayloadException("Creating user requires unique userName");
}
//second 'if' for controller updateUser method
if (userService.findByUserName(userDto.getUserName())==null) {
throw new InvalidPayloadException("Updating unexisting users is not allowed");
}
}
}
控制器:
这里我们对验证者有两种相反的情况:
1 创建具有唯一用户名的用户
2 更新用户 - 必需的用户名
@Controller
@RequestMapping(value = "/api/users")
public class ApiUserController extends ExceptionsResolver {
@Autowired
private UserService userService;
@Autowired
private UserDtoValidator userDtoValidator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(userDtoValidator);
}
@RequestMapping(consumes = "application/json", produces = "application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity createUser(@Valid @RequestBody UserDto userDto) throws JsonProcessingException {
userService.saveUser(userDto);
return new ResponseEntity(userDto, HttpStatus.ACCEPTED);
}
@RequestMapping(value = "/{userName}", consumes = "application/json", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<UserDto> updateUser(@Valid @RequestBody UserDto userDto, @PathVariable String userName) {
return new ResponseEntity("User updated", HttpStatus.ACCEPTED);
}
}
顺便说一句,我知道 PUT 应该创建新的,但在这里我只需要 PUT 进行更新。