springboot Restful 風格開發

2021-10-09 18:12:05 字數 3125 閱讀 8578

到底什麼樣的風格才是restful風格呢?

1,約束請求命令如下:

get,獲取資源。例如:/employees表示獲取列表資源,/employees/表示獲取單個物件資源。

post,新增。例如:/employees,body為json物件,表示新增。

put,更新。例如:/employees/,body為json物件,表示更新。

delete,刪除。例如: /employees/,表示刪除。

2,約束返回結果: 返回資料為列表,則每個物件資源附加自己的資源鏈結、列表資源鏈結以及可操作性鏈結。

1 get 獲取所有員工

}返回所有員工,以及每個員工對應的可呼叫的介面。每次都是動態生成。相比傳統http模式,更加靈活。

從上面介面返回的_links–>self,獲取指定員工資訊

}post 請求新增使用者

,

"employees":}

}

put 請求 更新員工資訊,3代表指定員工id,具體資訊通過data傳遞。

,

"employees":}

}

delete 請求 刪除指定員工 3代表指定員工id

curl -x delete  http://localhost:8080/employees/3
如果刪除成功,此介面沒有返回結果。

使用h2作為記憶體資料庫,建立員工

@configuration

class loaddatabase ;}

}

使用的jar包

com.h2database

h2runtime

原理解釋:@configuration標註在類上,相當於把該類作為spring的xml配置檔案中的,作用為:配置spring容器(應用上下文)

@bean標註在方法上(返回某個例項的方法),等價於spring的xml配置檔案中的,作用為:註冊bean物件

(1)@bean註解在返回例項的方法上,如果未通過@bean指定bean的名稱,則預設與標註的方法名相同;

(2)@bean註解預設作用域為單例singleton作用域,可通過@scope(「prototype」)設定為原型作用域;

(3)既然@bean的作用是註冊bean物件,那麼完全可以使用@component、@controller、@service、@ripository等註解註冊bean,當然需要配置@componentscan註解進行自動掃瞄。

使用jpa訪問資料庫

inte***ce employeerepository extends jparepository

org.springframework.boot

spring-boot-starter-data-jpa

jpa建立實體類

@entity

class employee

employee(string firstname, string lastname, string role)

public string getname(

) public void setname(string name)

public long getid(

) public string getfirstname(

) public string getlastname(

) public string getrole(

) public void setid(long id)

public void setfirstname(string firstname)

public void setlastname(string lastname)

public void setrole(string role)

@override

public boolean equals(object o)

@override

public int hashcode(

) @override

public string tostring()'

;}

增加@controlleradvice註解,實現異常處理器:

@controlleradvice

class employeenotfoundadvice

}

class employeenotfoundexception extends runtimeexception 

}

二、restful的http服務

pom.xml增加hateoas依賴

org.springframework.boot

spring-boot-starter-hateoas

"/employees"

)collectionmodel> all(

)"/employees/"

)entitymodel one(@pathvariable long id)

@component

public class ordermodelassembler implements representationmodelassembler>

return ordermodel;

}}

視窗風格 視窗類風格

視窗風格 ws border 新建乙個有邊框的視窗 ws caption 新建乙個有邊框 標題欄的視窗。不能和 ws dlgframe 一起用 ws child 新建乙個子視窗,不能和 ws popup 一起用 ws childwindow 和 ws child 風格一樣 ws clipchildr...

python風格規範 Python風格規範

請務必保持 的一致性 如果你正在編輯 花幾分鐘看一下周邊 然後決定風格.如果它們在所有的算術操作符兩邊都使用空格,那麼你也應該這樣做.如果它們的注釋都用標記包圍起來,那麼你的注釋也要這樣.制定風格指南的目的在於讓 有規可循,這樣人們就可以專注於 你在說什麼 而不是 你在怎麼說 我們在這裡給出的是全域...

python風格編碼 Python編碼風格 概述

對於 python 而言,pep 8 已成為大多數專案遵循的風格指南 它給出了乙個高度可讀,視覺友好的編碼風格。每個 python 開發者應該閱讀一下 這裡是為你提取出來的最重要的要點 from pymongo import mongoclient import gridfs,datetime,ti...