【发布时间】:2017-11-27 21:05:33
【问题描述】:
我正在使用 Spring Boot 1.5.3、Spring Data REST、Spring HATEOAS。 Spring Data REST 非常棒,做得很完美,但有时它需要自定义业务逻辑,因此我需要创建一个自定义控制器。
我将使用 @RepositoryRestController 来利用 Spring Data REST 功能 (http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers)。
因为 Spring Data REST 默认使用 HATEOAS,所以我正在使用它。我需要这样的控制器:
@RepositoryRestController
@RequestMapping(path = "/api/v1/workSessions")
public class WorkSessionController {
@Autowired
private EntityLinks entityLinks;
@Autowired
private WorkSessionRepository workSessionRepository;
@Autowired
private UserRepository userRepository;
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.POST, path = "/start")
public ResponseEntity<?> start(@RequestBody(required = true) CheckPoint checkPoint) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (checkPoint == null) {
throw new RuntimeException("Checkpoint cannot be empty");
}
if (workSessionRepository.findByAgentUsernameAndEndDateIsNull(auth.getName()).size() > 0) {
// TODO return exception
throw new RuntimeException("Exist a open work session for the user {0}");
}
// ...otherwise it's opened a new work session
WorkSession workSession = new WorkSession();
workSession.setAgent(userRepository.findByUsername(auth.getName()));
workSession.setCheckPoint(checkPoint);
workSession = workSessionRepository.save(workSession);
Resource<WorkSession> resource = new Resource<>(workSession);
resource.add(entityLinks.linkFor(WorkSession.class).slash(workSession.getId()).withSelfRel());
return ResponseEntity.ok(resource);
}
}
因为参数 CheckPoint 必须是一个存在的资源,我希望客户端发送资源的链接(就像你可以在 Spring Data REST POST 方法中做的那样)。 不幸的是,当我尝试这样做时,服务器端我收到了一个空的 CheckPoint 对象。
我已经读过Resolving entity URI in custom controller (Spring HATEOAS) 和converting URI to entity with custom controller in spring data rest? 尤其是Accepting a Spring Data REST URI in custom controller。
我想知道是否有最佳实践来避免将 id 暴露给客户端,遵循 HATEOAS 原则。
【问题讨论】:
-
请显示您的 POST 请求 url 和正文。我认为您应该将 CheckPoint ID 作为参数传递给控制器方法..
-
@Cepr0 这是网址:localhost:8080/api/v1/workSessions/start 这是正文 {"checkPoint":"localhost:8080/api/v1/checkPoints/1"}
-
看我的回答...
标签: spring spring-mvc spring-data-rest