SpringMVC REST風格深入詳細講解
REST簡介
REST介紹
- REST(Representational State Transfer),表現(xiàn)形式狀態(tài)轉(zhuǎn)換
傳統(tǒng)風格資源描述形式
REST風格描述形式
優(yōu)點
- 隱藏資源的訪問行為,無法通過地址得知對資源是何種操作
- 書寫簡化
RESTful介紹
按照REST風格訪問資源時使用==行為動作==區(qū)分對資源進行了何種操作
- http://localhost/users 查詢?nèi)坑脩粜畔?GET(查詢)
- http://localhost/users/1查詢指定用戶信息 GET(查詢)
- http://localhost/users添加用戶信息 POST(新增/保存)
- http://localhost/users修改用戶信息 PUT(修改/更新)
- http://localhost/users/1刪除用戶信息 DELETE(刪除)
根據(jù)REST風格對資源進行訪問稱為RESTful
注意事項
- 上述行為是約定方式,約定不是規(guī)范,可以打破,所以稱REST風格,而不是REST規(guī)范
- 描述模塊的名稱通常使用復數(shù),也就是加s的格式描述,表示此類資源,而非單個資源,例如:users、books、accounts……
RESTful入門案例
快速入門
做法:在Controller中定義方法時設定"http請求動作(請求方式)"和"設定請求參數(shù)(路徑變量)"
@Controller public class UserController { //設置當前請求方法為POST,表示REST風格中的添加操作 @RequestMapping(value = "/users",method = RequestMethod.POST) @ResponseBody public String save(){ System.out.println("user save..."); return "{'module':'user save'}"; } //設置當前請求方法為DELETE,表示REST風格中的刪除操作 //@PathVariable注解用于設置路徑變量(路徑參數(shù)),要求路徑上設置對應的占位符,并且占位符名稱與方法形參名稱相同 @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE) @ResponseBody public String delete(@PathVariable Integer id){ System.out.println("user delete..." + id); return "{'module':'user delete'}"; } //設置當前請求方法為PUT,表示REST風格中的修改操作 @RequestMapping(value = "/users",method = RequestMethod.PUT) @ResponseBody public String update(@RequestBody User user){ System.out.println("user update..."+user); return "{'module':'user update'}"; } //設置當前請求方法為GET,表示REST風格中的查詢操作 //@PathVariable注解用于設置路徑變量(路徑參數(shù)),要求路徑上設置對應的占位符,并且占位符名稱與方法形參名稱相同 @RequestMapping(value = "/users/{id}" ,method = RequestMethod.GET) @ResponseBody public String getById(@PathVariable Integer id){ System.out.println("user getById..."+id); return "{'module':'user getById'}"; } //設置當前請求方法為GET,表示REST風格中的查詢操作 @RequestMapping(value = "/users",method = RequestMethod.GET) @ResponseBody public String getAll(){ System.out.println("user getAll..."); return "{'module':'user getAll'}"; } }
@PathVariable介紹
- 名稱:@PathVariable
- 類型:形參注解
- 位置:SpringMVC控制器方法形參定義前面
- 作用:綁定路徑參數(shù)與處理器方法形參間的關(guān)系,要求路徑參數(shù)名與形參名一一對應
?
@RequestBody、@RequestParam、@PathVariable區(qū)別和應用
區(qū)別
- @RequestParam用于接收url地址傳參或表單傳參
- @RequestBody用于接收json數(shù)據(jù)
- @PathVariable用于接收路徑參數(shù),使用{參數(shù)名稱}描述路徑參數(shù)
應用
- 后期開發(fā)中,發(fā)送請求參數(shù)超過1個時,以json格式為主,@RequestBody應用較廣
- 如果發(fā)送非json格式數(shù)據(jù),選用@RequestParam接收請求參數(shù)
- 采用RESTful進行開發(fā),當參數(shù)數(shù)量較少時,例如1個,可以采用@PathVariable接收請求路徑變量,通常用于傳遞id值
REST快速開發(fā)
?
代碼中的問題
以上截圖中的代碼和之前寫的UserController中的方法類似,其中圖中兩個方法都有三處是有問題的,可以進行優(yōu)化。存在的問題如下:
- 問題1:每個方法的@RequestMapping注解中都定義了訪問路徑/books,重復性太高。
- 問題2:每個方法的@RequestMapping注解中都要使用method屬性定義請求方式,重復性太高。
- 問題3:每個方法響應json都需要加上@ResponseBody注解,重復性太高。
Rest快速開發(fā)
解決以上三個問題
解決問題1:在Controller類上使用@RequestMapping定義共同的訪問路徑。
@Controller @RequestMapping("/books") public class BookController { @RequestMapping(method = RequestMethod.POST) public String save(@RequestBody Book book){ System.out.println("book save..." + book); return "{'module':'book save'}"; } @RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE) public String delete(@PathVariable Integer id){ System.out.println("book delete..." + id); return "{'module':'book delete'}"; } @RequestMapping(method = RequestMethod.PUT) public String update(@RequestBody Book book){ System.out.println("book update..."+book); return "{'module':'book update'}"; } @RequestMapping(value = "/{id}" ,method = RequestMethod.GET) public String getById(@PathVariable Integer id){ System.out.println("book getById..."+id); return "{'module':'book getById'}"; } @RequestMapping(method = RequestMethod.GET) public String getAll(){ System.out.println("book getAll..."); return "{'module':'book getAll'}"; } }
解決問題2:使用@GetMapping @PostMapping @PutMapping @DeleteMapping代替@RequestMapping(method=RequestMethod.XXX)
@Controller @RequestMapping("/books") public class BookController { // @RequestMapping( method = RequestMethod.POST) @PostMapping//使用@PostMapping簡化Post請求方法對應的映射配置 public String save(@RequestBody Book book){ System.out.println("book save..." + book); return "{'module':'book save'}"; } // @RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE) @DeleteMapping("/{id}") //使用@DeleteMapping簡化DELETE請求方法對應的映射配置 public String delete(@PathVariable Integer id){ System.out.println("book delete..." + id); return "{'module':'book delete'}"; } // @RequestMapping(method = RequestMethod.PUT) @PutMapping //使用@PutMapping簡化Put請求方法對應的映射配置 public String update(@RequestBody Book book){ System.out.println("book update..."+book); return "{'module':'book update'}"; } // @RequestMapping(value = "/{id}" ,method = RequestMethod.GET) @GetMapping("/{id}") //使用@GetMapping簡化GET請求方法對應的映射配置 public String getById(@PathVariable Integer id){ System.out.println("book getById..."+id); return "{'module':'book getById'}"; } // @RequestMapping(method = RequestMethod.GET) @GetMapping //使用@GetMapping簡化GET請求方法對應的映射配置 public String getAll(){ System.out.println("book getAll..."); return "{'module':'book getAll'}"; } }
- 名稱:@GetMapping @PostMapping @PutMapping @DeleteMapping
- 類型:方法注解
- 位置:基于SpringMVC的RESTful開發(fā)控制器方法定義上方
- 作用:設置當前控制器方法請求訪問路徑與請求動作,每種對應一個請求動作,例如@GetMapping對應GET請求
- 屬性: value(默認):請求訪問路徑
解決問題3:在Controller類上使用@RestController注解,等同于@Controller與@ResponseBody兩個注解組合功能
@RestController //使用@RestController注解替換@Controller與@ResponseBody注解,簡化書寫 @RequestMapping("/books") public class BookController { //方法省略了沒寫 }
- 名稱:@RestController
- 類型:類注解
- 位置:基于SpringMVC的RESTful開發(fā)控制器類定義上方
- 作用:設置當前控制器類為RESTful風格,等同于@Controller與@ResponseBody兩個注解組合功能
案例-基于RESTful頁面數(shù)據(jù)交互
案例效果和環(huán)境準備
案例效果
?
環(huán)境準備
//POJO實體類 public class Book { private Integer id; private String type; private String name; private String description; //重寫getter、setter、toString()方法... }
//SpringMVC容器初始化類 public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { return new Class[0]; } protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } protected String[] getServletMappings() { return new String[]{"/"}; } //亂碼處理 @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); return new Filter[]{filter}; } }
//SpringMVC配置類 @Configuration @ComponentScan({"com.moming.controller","com.moming.config"}) @EnableWebMvc public class SpringMvcConfig { }
代碼實現(xiàn)
制作SpringMVC控制器,并通過PostMan測試接口功能
@RestController @RequestMapping("/books") public class BookController { @PostMapping public String save(@RequestBody Book book){ System.out.println("book save ==> "+ book); return "{'module':'book save success'}"; } @GetMapping public List<Book> getAll(){ System.out.println("book getAll is running ..."); List<Book> bookList = new ArrayList<Book>(); Book book1 = new Book(); book1.setType("計算機"); book1.setName("SpringMVC入門教程"); book1.setDescription("小試牛刀"); bookList.add(book1); Book book2 = new Book(); book2.setType("計算機"); book2.setName("SpringMVC實戰(zhàn)教程"); book2.setDescription("一代宗師"); bookList.add(book2); Book book3 = new Book(); book3.setType("計算機叢書"); book3.setName("SpringMVC實戰(zhàn)教程進階"); book3.setDescription("一代宗師嘔心創(chuàng)作"); bookList.add(book3); return bookList; } }
靜態(tài)頁面資源(REST功能頁面)
鏈接:鏈接: https://pan.baidu.com/s/1u9GSGrDejwDDbFAe_inEGQ?pwd=aaey
設置對靜態(tài)資源的訪問放行
@Configuration public class SpringMvcSupport extends WebMvcConfigurationSupport { //設置靜態(tài)資源訪問過濾,當前類需要設置為配置類,并被掃描加載 @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { //當訪問/pages/????時候,從/pages目錄下查找內(nèi)容 registry.addResourceHandler("/pages/**") .addResourceLocations("/pages/"); registry.addResourceHandler("/js/**") .addResourceLocations("/js/"); registry.addResourceHandler("/css/**") .addResourceLocations("/css/"); registry.addResourceHandler("/plugins/**") .addResourceLocations("/plugins/"); } }
books.html前端頁面通過異步提交訪問后臺控制器
//添加 saveBook () { axios.post("/books",this.formData).then((res)=>{ }); }, //主頁列表查詢 getAll() { axios.get("/books").then((res)=>{ this.dataList = res.data; }); },
到此這篇關(guān)于SpringMVC REST深入詳細講解的文章就介紹到這了,更多相關(guān)SpringMVC REST內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Mybatis-plus策略自動更新數(shù)據(jù)庫時間失敗問題解決
這篇文章主要介紹了使用Mybatis-plus策略自動更新數(shù)據(jù)庫時間失敗問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10JAVA實現(xiàn)連接本地打印機并打印文件的實現(xiàn)代碼
這篇文章主要介紹了JAVA實現(xiàn)連接本地打印機并打印文件的實現(xiàn)代碼,需要的朋友可以參考下2019-10-10UniApp?+?SpringBoot?實現(xiàn)支付寶支付和退款功能
這篇文章主要介紹了UniApp?+?SpringBoot?實現(xiàn)支付寶支付和退款功能,基本的?SpringBoot?的腳手架,可以去IDEA?自帶的快速生成腳手架插件,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-06-06JAVASE精密邏輯控制過程詳解(分支和循環(huán)語句)
在一個程序執(zhí)行的過程中各條語句的執(zhí)行順序?qū)Τ绦虻慕Y(jié)果是有直接影響的,這篇文章主要給大家介紹了關(guān)于JAVASE精密邏輯控制(分支和循環(huán)語句)的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04Spring實戰(zhàn)之Qualifier注解用法示例
這篇文章主要介紹了Spring實戰(zhàn)之Qualifier注解用法,結(jié)合實例形式詳細分析了spring Qualifier注解相關(guān)配置、定義與使用方法,需要的朋友可以參考下2019-12-12MyBatis通過JDBC數(shù)據(jù)驅(qū)動生成的執(zhí)行語句問題
這篇文章主要介紹了MyBatis通過JDBC數(shù)據(jù)驅(qū)動生成的執(zhí)行語句問題的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08