美文网首页
springboot hateoas初体验

springboot hateoas初体验

作者: 前进的码农 | 来源:发表于2020-10-28 10:28 被阅读0次

    官方参考文档

    https://spring.io/guides/tutorials/rest/
    https://spring.io/projects/spring-hateoas#samples

    实操

    概念啥的玩意自己网上百度自己查

    引入pom

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-hateoas</artifactId>
            </dependency>
    

    编写bean

    @Data
    public class UserVo extends RepresentationModel<UserVo> implements Serializable {
        private final String name;
        @JsonCreator
        public UserVo(@JsonProperty("name") String name) {
            this.name = name;
        }
    }
    

    编写controller

    @RestController
    @RequestMapping("user")
    public class UserController {
    
        @GetMapping("get")
        public Object user(){
            UserVo userVo = new UserVo("张三");
            //添加自身地址信息
            userVo.add(linkTo(methodOn(UserController.class).user()).withSelfRel()).
                    //添加额外地址信息
                    add(linkTo(methodOn(UserController.class).info(1L)).withRel("info"));
            return userVo;
        }
        @GetMapping("info/{id}")
        public Object info(@PathVariable Long id){
            return "info"+id;
        }
    }
    
    

    最终效果

    image.png
    image.png

    完整代码地址

    https://gitee.com/ethanlab/hateoas

    相关文章

      网友评论

          本文标题:springboot hateoas初体验

          本文链接:https://www.haomeiwen.com/subject/urjqvktx.html