這篇文章給大家介紹SpringMVC中REST風格的請求有哪些,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
一、 在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請求:
@RequestMapping(value="/student",method=RequestMethod.GET)
public ModelAndView toAddPage(){
ModelAndView mView=new ModelAndView();
mView.addObject("employee",new Employee());
mView.setViewName("add-stu");
mView.addObject("departments", departmentDao.getDepartments());
return mView;
}POST請求:
@RequestMapping(value="/student",method=RequestMethod.POST)
public String addStu(Employee employee){
employeeDao.save(employee);
return "redirect:/show" ;
}DELETE請求:
@RequestMapping(value="/student/{id}",method=RequestMethod.DELETE)
public String deleteStu(@PathVariable(value="id") Integer id){
employeeDao.delete(id);
return "redirect:/show" ;
}PUT請求:
@RequestMapping(value="/student",method=RequestMethod.PUT)
public String Update(@RequestParam(value="id")Integer id,Employee employee){
employeeDao.save(employee);
return "redirect:/show" ;
}三、將POST請求轉化為put請求和delele請求
1.在web.xml文件中配置HiddenHttpMethodFilter過濾器:
<!-- HiddenHttpMethodFilter過濾器可以將POST請求轉化為put請求和delete請求! --> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.在表單域中需要攜帶一個name值為_method,value值為put或者delete的參數,如下所示:
<form action="" method="post"> <input type="hidden" name="_method" value="delete"> </form>
<form:form action="${pageContext.request.contextPath}/student" method="post" modelAttribute="employee">
<c:if test="${empty employee.id }">
姓名:<form:input path="lastName"/><br>
</c:if>
<c:if test="${!empty employee.id }">
姓名:<form:input path="lastName" readonly="true"/><br>
<form:hidden path="id"/>
<input type="hidden" name="_method" value="put">
</c:if>
郵箱:<form:input path="email"/><br>
<%
Map<String,Object>map=new HashMap<String,Object>();
map.put("1","Male");
map.put("0", "Female");
request.setAttribute("genders", map);
%>
性別:<form:radiobuttons path="gender" items="${genders}"/><br>
部門:<form:select path="department.id" items="${departments}" itemValue="id" itemLabel="departmentName"></form:select><br>
<input type="submit" value="提交">
</form:form>最后在Controller層調用即可。根據@RequestMapping的value值以及攜帶的參數、請求方式查找匹配函數。
關于SpringMVC中REST風格的請求有哪些就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。