簡體   English   中英

如何在不修改整個響應的情況下基於HATEOAS返回URL?

[英]How to return URLs based on HATEOAS without modifying the whole response?

我已經使用Spring Boot開發了一項服務。 這是代碼(簡體):

@RestController
@RequestMapping("/cars")
public class CarController {
    @Autowired
    private CarService carService;

    @Autowired
    private CarMapper carMapper;

    @GetMapping("/{id}")
    public CarDto findById(@PathVariable Long id) {
        Car car = carService.findById(id);
        return carMapper.mapToCarDto(car);
    }
}

CarMapper是使用mapstruct定義的。 這是代碼(也已簡化):

@Mapper(componentModel="spring",
        uses={ MakeModelMapper.class })
public interface CarMapper {
    @Mappings({
        //fields omitted
        @Mapping(source="listaImagenCarro", target="rutasImagenes")
    })
    CarDto mapToCarDto(Car car);

    String CAR_IMAGE_URL_FORMAT = "/cars/%d/images/%d"
    /*
        MapStruct will invoke this method to map my car image domain object into a String. Here's my issue.
    */
    default String mapToUrl(CarImage carImage) {
        if (carImage == null) return null;
        return String.format(
                   CAR_IMAGE_URL_FORMAT,
                   carImage.getCar().getId(),
                   carImage.getId()
               );
    }
}

調用服務時得到的JSON響應:

{
    "id": 9,
    "make": { ... },
    "model": { ... },
    //more fields...
    //the urls for the car images
    "images": [
        "/cars/9/images/1"
    ]
}

我需要images字段返回有關服務器和我的應用程序部署路徑的有效URL。 例如,如果我通過端口8080使用localhost部署應用程序,我想獲得以下信息:

{
    "id": 9,
    "make": { ... },
    "model": { ... },
    //more fields...
    "imagenes": [
        "http://localhost:8080/cars/9/images/1"
    ]
}

我已經審查了構建超媒體驅動的RESTful Web服務 ,這似乎是我想要的。 除了只需要這些URL以外,我不想更改整個響應對象。

還有另一種方法可以實現嗎?

Spring HATEOAS為此提供了LinkBuilder服務。

請嘗試以下操作:

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
//...//

linkTo(methodOn(CarController.class).findById(9)).withRel("AddYourRelHere");

這應該輸出指向您資源的絕對URL。 您未遵循HAL約定,因此應更改或刪除“ withRel(“”)“部分

您可以將其添加到要更改的特定DTO中:

CarDto dto = carMapper.mapToCarDto(car);
if(dto.matches(criteria)){
    dto.setUrl(linkTo...);
}
return dto;

順便說一下,所有這些都顯示在您提到的教程的“創建RestController”部分中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM