SpringBoot之Hypermedia-Driven RESTful Web Service

来源:互联网 发布:土耳其人 知乎 编辑:程序博客网 时间:2024/05/01 05:46

通过org.springframework.hateoas.ResourceSupport来处理超媒体部分数据结构。

假设要提供的超媒体数据结构如下:

{    "content": "Hello, World!",    "_links": {        "self": {            "href": "http://localhost:8080/greeting?name=World"        }    }}

下面是提供Hypermedia-Driven RESTful Web Service程序的主要代码:
1 model类

package hypermedia.restfull.web.service.hello;import org.springframework.hateoas.ResourceSupport;import com.fasterxml.jackson.annotation.JsonCreator;import com.fasterxml.jackson.annotation.JsonProperty;public class Greeting extends ResourceSupport {    private final String content;    @JsonCreator    public Greeting(@JsonProperty("content")String content){        this.content = content;    }    public String getContent() {        return content;    }}

说明:

To model the greeting representation, you create a resource representation class. As the _links property is a fundamental property of the representation model, Spring HATEOAS ships with a base class ResourceSupport that allows you to add instances of Link and ensures that they are rendered as shown above.

2 controller类

package hypermedia.restfull.web.service.hello;import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;import org.springframework.http.HttpEntity;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class GreetingController {    private static final String TEMPLATE = "Hello, %s!";    @RequestMapping("/greeting")    public HttpEntity<Greeting> greeting(@RequestParam(value="name", required=false, defaultValue="World")String name){        Greeting greeting = new Greeting(String.format(TEMPLATE, name));        greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());        return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);    }}

说明:

Because the @RestController annotation is present on the class, an implicit @ResponseBody annotation is being added onto the greeting method. This causes Spring MVC to render the returned HttpEntity and its payload, the Greeting, directly to the response.

Both linkTo(…) and methodOn(…) are static methods on ControllerLinkBuilder that allow you to fake a method invocation on the controller. The LinkBuilder returned will have inspected the controller method’s mapping annotation to build up exactly the URI the method is mapped to.

3 application类

package hypermedia.restfull.web.service.hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}
0 0
原创粉丝点击