1. 程式人生 > >SpringMVC-03 RestFul和控制器

SpringMVC-03 RestFul和控制器

# SpringMVC-03 RestFul和控制器 ## 控制器Controller - 控制器複雜提供訪問應用程式的行為,通常通過介面定義或註解定義兩種方法實現。 - 控制器負責解析使用者的請求並將其轉換為一個模型。 - 在Spring MVC中一個控制器類可以包含多個方法 - 在Spring MVC中,對於Controller的配置方式有很多種 ### RequestMapping **註解方式是平時使用的最多的方式!** **@RequestMapping** - @RequestMapping註解用於對映url到控制器類或一個特定的處理程式方法。可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。 - 為了測試結論更加準確,我們可以加上一個專案名測試 **只註解在方法上面** ```java @Controller public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } } ``` > 訪問路徑:http://localhost:8080 / 專案名 / h1 ​ **同時註解類與方法** ```java @Controller @RequestMapping("/admin") public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } } ``` >訪問路徑:http://localhost:8080 / 專案名/ admin /h1 ## RestFul 風格 ### 1.概念 Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟體可以更簡潔,更有層次,更易於實現快取等機制。 ### 2.功能 資源:網際網路所有的事物都可以被抽象為資源 資源操作:使用`POST`、`DELETE`、`PUT`、`GET`,使用不同方法對資源進行操作。 分別對應 新增、 刪除、修改、查詢。 **傳統方式操作資源** :通過不同的引數來實現不同的效果,方法單一,post 和 get ​ http://localhost:8080/item/queryItem.action?id=1 查詢,GET ​ http://localhost:8080/item/saveItem.action 新增,POST ​ http://localhost:8080/item/updateItem.action 更新,POST ​ http://localhost:8080/item/deleteItem.action?id=1 刪除,GET或POST **使用RESTful操作資源** :可以通過不同的請求方式來實現不同的效果。如下:請求地址一樣,但是功能可以不同。 ​ http://localhost:8080/item/1 查詢,GET ​ http://localhost:8080/item 新增,POST ​ http://localhost:8080/item 更新,PUT ​ http://localhost:8080/item/1 刪除,DELETE ### 3.案例測試 #### 3.1 編寫web.xml ```xml
springmvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 springmvc /
``` #### 3.2 建立springmvc.xml ```xml
``` #### 3.3 新建一個Controller類 ```java @Controller public class RestFulController { //對映訪問路徑 @RequestMapping("/commit/{p1}/{p2}") public String index(@PathVariable int p1, @PathVariable int p2, Model model){ int result = p1+p2; //Spring MVC會自動例項化一個Model物件用於向檢視中傳值 model.addAttribute("msg", "結果:"+result); //返回檢視位置 return "test"; } } ``` #### 3.4 建立test.jsp ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %>
RestFul ${msg} ``` #### 3.5 配置Tomcat,測試 **思考:使用路徑變數的好處?** 1. - 使路徑變得更加簡潔; - 獲得引數更加方便,框架會自動進行型別轉換; - 通過路徑變數的型別可以約束訪問引數,如果型別不一樣,則訪問不到對應的請求方法,如這裡訪問是的路徑是`/commit/1/a`,則路徑與方法不匹配,而不會是引數轉換失敗; #### 3.6 修改引數型別 ```java @Controller public class RestFulController { //對映訪問路徑 @RequestMapping("/commit/{p1}/{p2}") public String index(@PathVariable int p1, @PathVariable String p2, Model model){ String result = p1+p2; //Spring MVC會自動例項化一個Model物件用於向檢視中傳值 model.addAttribute("msg", "結果:"+result); //返回檢視位置 return "test"; } } ``` #### 3.7 指定請求型別 **使用method屬性指定請求型別** 用於約束請求的型別,可以收窄請求範圍。指定請求謂詞的型別如`GET`,` POST`,` HEAD`, `OPTIONS`, `PUT`, `PATCH`, `DELETE`, `TRACE`...... 我們來測試一下: - 增加一個方法: ```java //對映訪問路徑,必須是POST請求 @RequestMapping(value = "/hello",method = {RequestMethod.POST}) public String index2(Model model){ model.addAttribute("msg", "hello!"); return "test"; } ``` - 我們使用瀏覽器位址列進行訪問預設是Get請求,會報錯405: ​ **如果將POST修改為GET則正常了** ### HTTP 請求 我們正常傳送HTTP請求,可以正常傳送的只有`GET`、`POST`,而在RestFul風格中`PUT`、`DELETE`,`PATCH`則不能直接傳送,可以使用以下方法: #### 1.配置web.xml ```xml HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /* ``` #### 2.編寫form表單 ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> $Title$

姓名:


性別:


年齡:


``` > form表單中有一個隱藏的`input`,name必須為`_method`,value="xxx"即為xxx請求。 #### 3.編寫Controller類 ```java @Controller public class RestFulController { @PutMapping("/put") @ResponseBody public String index3(HttpServletRequest req, HttpServletResponse resp){ String name = req.getParameter("name"); String sex = req.getParameter("sex"); String age = req.getParameter("age"); return "name:" + name + ",sex:" + sex + ",age:" + age; } } ``` > 注意: > > 這裡可以使用 **@RequestMapping(value = "/put",method = {RequestMethod.PUT})** > > 也可以直接使用: @PutMapping("/put") > > 由上面可以看出: > > **是method設定不同型別的請求** > > **或者** > > **@GetMapping > @PostMapping > @PutMapping > @DeleteMapping > @PatchMapping** #### 4.測試 ​ 會發現填寫的`中文`都成為了`?`,這時候可以嘗試在`web.xml`中設定`字元過濾器`: ```xml encoding org.springframework.web.filter.CharacterEncodingFilter encoding utf-8 forceEncoding true encoding /* ``` **這種過濾器對大部分中文亂碼都有用了,但是還有一種情況為json中文亂碼:** **匯入依賴** ```xml com.fasterxml.jackson.core jackson-core 2.9.9 com.fasterxml.jackson.core jackson-databind 2.9.9 ``` **在springmvc.xml中配置** ```xml text/plain;charset=UTF-8 text/html;charset=UTF-8 application/json;charset=UTF-8 ``` ![6](https://gitee.com/MoYu-zc/picgo/raw/master/img/20210214200046.png) > 個人部落格為: > [MoYu's Github Blog](https://www.moyuzc.cn/) > [MoYu's Gitee Blog](https://moyu-zc.git