1. 程式人生 > 其它 >學習SpringBoot第一天(構建RESTful Web 服務)

學習SpringBoot第一天(構建RESTful Web 服務)

第一步(構建springboot專案)


第二步(建立實體類)

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

第三步(建立控制器)

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @RestController :相當於@ResponseBody + @Controller合在一起的作用;
 * 如果只是使用@RestController註解Controller,則Controller中的方法無法返回jsp頁面,
 * 配置的檢視解析器InternalResourceViewResolver不起作用,返回的內容就是Return 裡的內容。
 *
 */
@RestController
public class GreetingController {
//    %s : 可以替換為請求的引數
    private static final String template="Hello,%s";
//  AtomicLong : 是對長整形進行原子操作
    private final AtomicLong counter=new AtomicLong();

    /**
     * @GetMapping: 請求方式為get請求(http://localhost:8080/greeting)
     * @RequestParam :將請求引數繫結到控制器;value : 引數值;defaultValue : 預設值
     * incrementAndGet():每次預設加一
     * @return : 返回型別為JSON,因為預設情況下web Starter 包含Jackson,Jackson庫會自動將Greeting類轉換為JSON;
     */
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name",defaultValue = "World") String name){
        return new Greeting(counter.incrementAndGet(),String.format(template,name));
    }
}

第四步(測試)