Java Backend ( Spring )

Request Method

  • RequestMapping("/asset")
    此種寫法的情境下,不論是透過 Get 或是 Post 送出路徑為 "/asset" 的請求,都會對應到同樣的 Controller。
    Get Method 以及 Post Method 並沒有硬性規定必須依功能區分使用,如 Get 只能讀取、 Post 只能新增,兩者差別只在於傳遞資料的方式不同,也因為各自的傳遞資料特性,有較適合的使用時機。
    • Get 使用直接加在請求路徑(網址)的方式傳遞資料

      1. Request Param - 請求參數
        ex.
        前端送出 /asset?編號=1&名稱=SmartPole#1 的請求
        上述的寫法於後端接收時會指定資料的 key (資料的名稱)
        ​​​​​​​​​​​​@RequestMapping("/asset")
        ​​​​​​​​​​​​@RequestParam(name = "編號") int id,
        ​​​​​​​​​​​​@RequestParam(name = "名稱") string name
        
      2. Path Variable - 路徑變數
        ex.
        前端送出 /asset/1/SmartPole#1 的 請求
        後端則用以下方式接收
        ​​​​​​​​​​​​@RequestMapping("/asset/{id}/{name}")
        ​​​​​​​​​​​​@PathVariable(name = "id") int id,
        ​​​​​​​​​​​​@PathVariable(name = "name") string name,
        
        • API Document 常用變數表示方式:
          1./asset/:id
          2./asset/{id}
    • Post 則是透過 Path Variable( 通常用於指定目標 ) & Method (將資料放在 Message Body ) 傳遞資料 (通常為 JSON 格式),傳遞資料的格式需透過 Http Header 定義,ex. Content-Type: application/json
      前端常用 Method

      • JSON.parse("json") - JSON 轉換成 Object
      • JSON.stringify(data) - Object 轉換成 JSON

Restful

  • Post ( C ) - 新增
    1. 新增一筆 asset 資料 - Post - /asset
  • Get ( R ) - 查詢
    1. 查詢多筆(全部) asset 資料 - Get - /asset
    2. 查詢主鍵 (Primary Key) 為 1 的 asset - Get - /asset/1
  • Put / Post ( U ) - 修改
    1. 修改多筆(全部) asset 資料 - Put/Post - /asset
    2. 修改主鍵為 1 的 asset 資料 - Put/Post - /asset/1,若不存在此筆資料,則回傳錯誤
  • Delete ( D ) - 刪除
    1. 刪除多筆(全部) asset 資料 - Delete - /asset
    2. 修改主鍵為 1 的 asset 資料 - Delete - /asset/1,若不存在此筆資料,則回傳錯誤

發送 Http Request

  • Spirng 可使用 RestTemplate 使用預設值發送 Http Request,減少繁瑣的 Request 設定 ( 建立連線, 定義 Headers 等 )。
RestTemplate restTemplate = new RestTemplate();

// 回傳完整 Response Entity,可使用 getBody() 取得內容。
restTemplate.getForEntity(url, {entity.class});

// 僅回傳 Response Body
restTemplate.getForObject(url, {entity.class});

AJAX ( Asynchronous JavaScript and XML )

References

HttpChallenge
API List 範例
AJAX