我正在读这篇文章http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_writing_an_annotated_handler,我决定使用带注释的处理程序方法。如何做弹簧数据验证
本指南缺少一些东西:如何验证?断言或抛出异常或以某种方式使用魔术注释(就像Java的一切)。
想象一下,我不想让一个名字叫“约翰”的人。
我正在读这篇文章http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_writing_an_annotated_handler,我决定使用带注释的处理程序方法。如何做弹簧数据验证
本指南缺少一些东西:如何验证?断言或抛出异常或以某种方式使用魔术注释(就像Java的一切)。
想象一下,我不想让一个名字叫“约翰”的人。
做的是使用温泉Bean验证集成http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html
这允许基于注解豆验证的典型的东西。
如果我理解的很好,例如,如果您的API端点有一个请求POST/users并且主体包含用于在数据库中创建新用户的数据,那么您需要先验证如果请求中提供的用户名尚未在数据库中使用,对吧?
如果这是您要查找的内容,则应该使用存储库控制器而不是事件处理程序。
继续我前面的例子,这是处理POST /用户请求验证的控制器验证用户名尚未使用,然后如果一切顺利,新用户将被保存,否则,客户端将接收到错误消息,并且该事务将不会在数据库中执行。
@RepositoryRestController
public class UserController {
private final UserRepository repository;
@Autowired
public UserController(UserRepository repository) {
this.repository = repository;
}
@RequestMapping(method = RequestMethod.POST, path = "/users")
public @ResponseBody ResponseEntity<?> addUser(@RequestBody User user) {
if (repository.findByUsername(user.getUsername()) == null) {
repository.save(user);
Resource<User> resource;
resource = new Resource<>(user);
return new ResponseEntity<Resource>(resource, HttpStatus.CREATED);
}
else {
ErrorResponse error = new ErrorResponse(ErrorType.EMAIL_ALREADY_EXISTS);
Resource<ErrorResponse> resource = new Resource<>(error);
return new ResponseEntity<>(resource, HttpStatus.CONFLICT);
}
}
}
http://www.baeldung.com/spring-data-rest-validators – Cepr0
[事件侦听器(http://docs.spring.io/spring-data/rest/docs/current/reference/ html /#events.application-listener):https://github.com/olivergierke/spring-restbucks/blob/master/src/main/java/org/springsource/restbucks/order/web/OrderControllerEventListener.java [Annotated处理程序](http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_writing_an_annotated_handler):https://github.com/Cepr0/restvotes/blob/master/src/main /java/restvotes/web/eventHandler/PollEventHandler.java – Cepr0