SpringMVC的REST風格的四種請求方式,springmvcrest
一、 在HTTP 協議裡面,四個表示操作方式的動詞:GET、POST、PUT、DELETE。
·它們分別對應四種基本操作:
1、GET ====== 獲 取資源
2、POST ======建立資源
3、PUT======= 更新資源
4、DELETE==== 刪除資源
二、REST:即 Representational State Transfer。(資源)表現層狀態轉化。是目前最流行的一種互連網軟體架構。它結構清晰、符合標準、易於理解、擴充方便, 所以正得到越來越多網站的採用。
我們可以通過rest風格預留位置方式,利用@PathVariable註解將佔位符的值賦給調用方法參數,實現結果:
-
-
- /某路徑/1 HTTP GET : 得到 id = 1 的 一條資料
- /某路徑/1 HTTP DELETE: 刪除 id = 1的 一條資料
- /某路徑/1 HTTP PUT: 更新id = 1的 一條資料
- /某路徑 HTTP POST: 新增一條資料
實現方式(REST風格四種請求方式的調用):
我們通過@RequestMapping映射請求中的method參數實現四種請求方式的調用,以下為範例程式碼。
GET請求:
1 @RequestMapping(value="/student",method=RequestMethod.GET) 2 public ModelAndView toAddPage(){ 3 ModelAndView mView=new ModelAndView(); 4 mView.addObject("employee",new Employee()); 5 mView.setViewName("add-stu"); 6 mView.addObject("departments", departmentDao.getDepartments()); 7 return mView; 8 }
POST請求:
1 @RequestMapping(value="/student",method=RequestMethod.POST) 2 public String addStu(Employee employee){ 3 employeeDao.save(employee); 4 return "redirect:/show" ; 5 }
DELETE請求:
1 @RequestMapping(value="/student/{id}",method=RequestMethod.DELETE) 2 public String deleteStu(@PathVariable(value="id") Integer id){ 3 employeeDao.delete(id); 4 return "redirect:/show" ; 5 }
PUT請求:
1 @RequestMapping(value="/student",method=RequestMethod.PUT) 2 public String Update(@RequestParam(value="id")Integer id,Employee employee){ 3 employeeDao.save(employee); 4 return "redirect:/show" ; 5 }
三、將POST請求轉化為put請求和delele請求
1.在web.xml檔案中配置HiddenHttpMethodFilter過濾器:
1 <!-- HiddenHttpMethodFilter過濾器可以將POST請求轉化為put請求和delete請求! -->2 <filter>3 <filter-name>hiddenHttpMethodFilter</filter-name>4 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>5 </filter>6 <filter-mapping>7 <filter-name>hiddenHttpMethodFilter</filter-name>8 <url-pattern>/*</url-pattern>9 </filter-mapping>
2.在表單域中需要攜帶一個name值為_method,value值為put或者delete的參數,如下所示:
1 <form action="" method="post">2 <input type="hidden" name="_method" value="delete">3 </form>
1 <form:form action="${pageContext.request.contextPath}/student" method="post" modelAttribute="employee"> 2 <c:if test="${empty employee.id }"> 3 姓名:<form:input path="lastName"/><br> 4 </c:if> 5 <c:if test="${!empty employee.id }"> 6 姓名:<form:input path="lastName" readonly="true"/><br> 7 <form:hidden path="id"/> 8 <input type="hidden" name="_method" value="put"> 9 </c:if>10 郵箱:<form:input path="email"/><br>11 <%12 Map<String,Object>map=new HashMap<String,Object>();13 map.put("1","Male");14 map.put("0", "Female");15 request.setAttribute("genders", map);16 %>17 性別:<form:radiobuttons path="gender" items="${genders}"/><br>18 部門:<form:select path="department.id" items="${departments}" itemValue="id" itemLabel="departmentName"></form:select><br>19 <input type="submit" value="提交">20 </form:form>
最後在Controller層調用即可。根據@RequestMapping的value值以及攜帶的參數、請求方式尋找匹配函數。