【前言】
面向資源的 restful 風格的 api 接口本著簡潔,資源,便于擴展,便于理解等等各項優勢,在如今的系統服務中越來越受歡迎。
.net平臺有webapi項目是專門用來實現restful api的,其良好的系統封裝,簡潔優雅的代碼實現,深受.net平臺開發人員所青睞,在后臺服務api接口中,已經逐步取代了輝煌一時mvc controller,更準確地說,合適的項目使用更加合適的工具,開發效率將會更加高效。
python平臺有tornado框架,也是原生支持了restful api,在使用上有了很大的便利。
java平臺的springmvc主鍵在web開發中取代了struts2而占據了更加有力的地位,我們今天著重講解如何在java springmvc項目中實現restful api。
【實現思路】
restful api的實現脫離不了路由,這里我們的restful api路由由spring mvc 的 controller來實現。
【開發及部署環境】
開發環境:windows 7 ×64 英文版
intellij idea 2017.2
部署環境:jdk 1.8.0
tomcat 8.5.5
測試環境:chrome
fiddler
【實現過程】
1、搭建spring mvc maven項目
這里的搭建步驟不再贅述,如有需要參考:http://m.ythuaji.com.cn/article/117995.html
2、新建控制器 studentcontroller
為了體現restful api 我們采用注解,requestmapping("/api/student")
具體的代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package controllers; import org.springframework.web.bind.annotation.*; @restcontroller @requestmapping ( "/api/student" ) public class studentcontroller { @requestmapping (method = requestmethod.get) public string get() { return "{\"id\":\"1\",\"name\":\"1111111111\"}" ; } @requestmapping (method = requestmethod.post) public string post() { return "{\"id\":\"2\",\"name\":\"2222222222\"}" ; } @requestmapping (method = requestmethod.put) public string put() { return "{\"id\":\"3\",\"name\":\"3333333333\"}" ; } @requestmapping (method = requestmethod.delete) public string delete() { return "{\"id\":\"4\",\"name\":\"4444444444\"}" ; } @requestmapping (value = "/{id}" ,method = requestmethod.get) public string get( @pathvariable ( "id" ) integer id) { return "{\"id\":\"" +id+ "\",\"name\":\"get path variable id\"}" ; } } |
這里有get,post,put,delete分別對應 查詢,添加,修改,刪除四種對資源的操作,即通常所說的crud。
spring mvc可實現restful的方式有@controller和@restcontroller兩種方式,兩種方式的區別如下:
@controller的方式實現如果要返回json,xml等文本,需要額外添加@responsebody注解,例如:
1
2
3
4
5
|
@responsebody //用于返回json數據或者text格式文本 @requestmapping (value = "/testjson" , method = requestmethod.get) public string testjson() { return "{\"id\":\"1001\",\"name\":\"zhangsan\"}" ; } |
@restcontroller方式不需要寫@responsebody,但是不能返回模型綁定數據和jsp視圖,只能返回json,xml文本,僅僅是為了更加方便返回json資源而已。
上述的rest方法中多寫了個get方法:
1
2
3
4
|
@requestmapping (value = "/{id}" ,method = requestmethod.get) public string get( @pathvariable ( "id" ) integer id) { return "{\"id\":\"" +id+ "\",\"name\":\"get path variable id\"}" ; } |
該方法可以直接在url拼接一個參數,更加方便對資源的定向訪問,例如查一個student list 可以默認空參數,而查詢對應的某一個student詳情信息,可以id=studentid 定向查詢單條,使得我們對資源的訪問更加快捷方便。
【系統測試】
運行系統,使用fiddler調用restful api接口:
1.get方式
2.post方式
3.put方式
4.delete方式
5.get/id方式
至此,可見我們的spring mvc restful api接口已經全部通過測試!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/qixiaoyizhan/p/7570010.html?utm_source=tuicool&utm_medium=referral