REST控制器返回Json中启用超媒体链接

超媒体作为应用状态引擎(Hypermedia as the Engine of Application State,HATEOAS) 是一种创建自我描述API消费的方式

API所返回的资源中会包含相关资源的链接,客户端只需要了解最少的API URL信息就能导航整个API。这种方式能够掌握API所

提供的资源之间的关系,客户端能够基于API的URL中所发现的关系对它们进行遍历。

带超级链接风格的HATEOAS被称为HAL(超文本应用语言,Hypertext Application Language)。这是一种在JSON中嵌入超链接

的简单通用格式。

在API项目中启用超媒体功能,需要在构建文件pom.xml文件中添加如下依赖:

<!--        启用超媒体功能-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
package tacos.web.api;

import lombok.Getter;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import tacos.Taco;

import java.util.Date;

/*
*taco资源
 */
@Relation(value = "taco",collectionRelation = "tacos")//声明生成Json时的对象名称
public class TacoResource extends RepresentationModel<TacoResource> {

    private static final IngredientResourceAssembler ingredientAssembler=new IngredientResourceAssembler(IngredientController.class,IngredientResource.class);

    @Getter
    private final String name;

    @Getter
    private final Date createdAt;

    @Getter
    private final CollectionModel<IngredientResource> ingredients;

    public TacoResource(Taco taco){
        this.name=taco.getName();
        this.createdAt=taco.getCreatedAt();
        this.ingredients=  ingredientAssembler.toCollectionModel(taco.getIngredients());
    }

}

package tacos.web.api;

import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import tacos.Taco;

/*
 *资源装配器,装配taco资源
 */
public class TacoResourceAssembler extends RepresentationModelAssemblerSupport<Taco,TacoResource> {

    public TacoResourceAssembler() {
        super(DesignTacoApiController.class, TacoResource.class);
    }

    public TacoResourceAssembler(Class<DesignTacoApiController> designTacoApiControllerClass, Class<TacoResource> tacoResourceClass) {
        super(designTacoApiControllerClass,tacoResourceClass);
    }

    @Override
    protected TacoResource instantiateModel(Taco entity) {
        return new TacoResource(entity);
    }

    @Override
    public TacoResource toModel(Taco entity) {
        return createModelWithId(entity.getId(),entity);
    }
}

package tacos.web.api;

import lombok.Getter;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import tacos.Ingredient;

/*
*Ingredient资源
 */
@Relation(value = "ingredient",collectionRelation = "ingredients")
public class IngredientResource extends RepresentationModel<IngredientResource> {

    @Getter
    private final String name;

    @Getter
    private final Ingredient.Type type;

    public IngredientResource(Ingredient entity){
        this.name=entity.getName();
        this.type=entity.getType();
    }
}
package tacos.web.api;

import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
import tacos.Ingredient;

/*
*装配资源
 */
public class IngredientResourceAssembler extends RepresentationModelAssemblerSupport<Ingredient,IngredientResource> {

    public IngredientResourceAssembler(Class<?> controllerClass, Class<IngredientResource> resourceType) {
        super(controllerClass, resourceType);
    }

    @Override
    protected IngredientResource instantiateModel(Ingredient entity) {
        return new IngredientResource(entity);
    }

    @Override
    public IngredientResource toModel(Ingredient entity) {
        return createModelWithId(entity.getId(),entity);
    }
}
package tacos.web.api;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.hateoas.CollectionModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tacos.Order;
import tacos.Taco;
import tacos.data.OrderRepository;
import tacos.data.TacoRepository;

import java.util.List;
import java.util.Optional;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;


@RestController//控件器中的所有处理器方法的返回值都要直接写入响应主体中,而不是将值放入模型Model中并传递给视图.
@RequestMapping(path = "/design",produces = {"application/json"})//指定API生成Json数据
@CrossOrigin(origins = "*")//允许跨域访问,允许来自任何域的客户端消费该API
public class DesignTacoApiController {
    private TacoRepository tacoRepo;
    private OrderRepository orderRepo;


    public DesignTacoApiController(TacoRepository tacoRepo, OrderRepository orderRepo) {
        this.tacoRepo = tacoRepo;
        this.orderRepo = orderRepo;
    }

  
    @GetMapping("/recent")
    public CollectionModel<TacoResource> recentTacos(){
        return getTacoResources();
    }
    //返回带有状态包装的实例
    @GetMapping("/recent2")
    public ResponseEntity<CollectionModel<TacoResource>> recentTacos2() {
        return new ResponseEntity<>(getTacoResources(), HttpStatus.OK);
    }

    private CollectionModel<TacoResource> getTacoResources() {
        PageRequest page=PageRequest.of(0,12, Sort.by("createdAt").descending());
        List<Taco> tacos=tacoRepo.findAll(page).getContent();

        CollectionModel<TacoResource> recentResources=new TacoResourceAssembler(DesignTacoApiController.class,TacoResource.class)
                .toCollectionModel(tacos);

        recentResources.add(linkTo(methodOn(DesignTacoApiController.class).recentTacos()).withRel("recents"));
        return recentResources;
    }

      
}

注意:低版本中所用到的类

  • ResourceSupport 就是现在 RepresentationModel
  • Resource 就是现在 EntityModel
  • Resources 就是现在 CollectionModel
  • PagedResources 就是现在 PagedModel
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值