2018/7/14

用Spring Boot開發的Restful Service範例程式

GET請求:
@RestController
@RequestMapping("/member")
public class WebController {

    @RequestMapping(value = "/firstname/{firstName}", method = {RequestMethod.GET})
    @ResponseBody
    public String queryFirstName(@PathVariable String firstName) {
        return firstName;
    }
}
然後可以用以下的網址來下請求
kiki是這個Web App的Context
使用PathVariable標註就可以取得URL的參數了,之後看要怎麼做後續的處理,這裡將queryFirstName這個method用ResponseBody標注起來,這樣此method回傳的東西就會變成此Service回應的Body,所以此Service就會回應Bloom

POST請求:
假設現在有一個以下的JSON進來:
{
    "firstName":"Frank",
    "lastName":"Vincent"
}
然後我需要準備一個對應的物件類別來封裝這個JSON:
package com.example.demo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Customer {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("firstName")
    @Expose
    private String firstName;
    @SerializedName("lastName")
    @Expose
    private String lastName;

    /**
     * No args constructor for use in serialization
     *
     */
    public Customer() {
    }

    /**
     *
     * @param id
     * @param lastName
     * @param firstName
     */
    public Customer(Integer id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public Customer(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Customer2{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}';
    }

}

那我就可以用以下程式碼去處理
@RestController
@RequestMapping("/member")
public class WebController {

    @RequestMapping(value = "/person", method = {RequestMethod.POST}, consumes = "application/json;charset=UTF-8")
    @ResponseBody
    public Customer addPerson(@RequestBody String requestBody) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();//創造Gson物件
        Customer u = gson.fromJson(requestBody, Customer.class);
        return new Customer(u.getFirstName(), u.getLastName());
    }

}
addPerson就會回傳以下json:
{
    "id": null,
    "firstName": "Frank",
    "lastName": "Vincent"
}

補充:將RestController放到別的套件就不能動了?
請參考這篇:https://stackoverflow.com/a/33040518/9512195
需要在main的那隻主程式加一個ComponentScan標註,告知還有誰是元件。


參考:
Spring Boot Reference Guide
Spring Boot Docs 2.0.3.RELEASE API

沒有留言:

張貼留言