javascript
restful post请求_猿蜕变9——一文搞定SpringMVC的RESTFul套路
看過之前的蛻變系列文章,相信你對springMVC有了一定的認識。對springMVC的Interceptor攔截器,也有了一定的認識。今天我們來開啟新討論,講一講springMVC對那一種休閑風的支付——RestFul。
每月底工廠君會根據后臺記錄篩選轉發文章前三位的朋友,給與獎勵,第一名100元,第二名50元,第三名30元的現金獎勵。行動力超強的你,關注公號,轉發文章,趕緊動起來吧!目前來看排名如下,胖子是我本人,不算的,大家多多努力噢。在路上同學,一直感謝你的默默關注,趕緊加我的微信,月底了,保持住,獎勵就是你的。
? ?? 猿蛻變同樣是一個原創系列文章,幫助你從一個普通的小白,開始掌握一些行業內通用的框架技術知識以及鍛煉你對系統設計能力的提升,完成屬于你的蛻變,更多精彩內容,敬請大家關注公主號猿人工廠,點擊猿人養成獲取!
都0202年了,再不會RestFul的URL風格的東西,你都不好意思出門了。Roy Fielding提出論文都20年了,這種清爽的,含有意義的URL幾乎所有的有點逼格的站點都在跟風靠攏。
REST的英文全稱是——Representational StateTransfer,中文含義是表現層狀態傳輸,目前主流的Web服務交互方案中,REST相比于SOAP(Simple Object Access protocol,簡單對象訪問協議)以及XML-RPC更加簡單明了,無論是對URL的處理還是對Payload的編碼,REST都傾向于用更加簡單輕量的方法設計和實現。
值得注意的是REST并沒有一個明確的標準,而更像是一種設計的風格。RESTful是一種網絡應用程序的設計風格和開發方式,基于HTTP,可以使用XML格式定義或JSON格式定義(就目前而言基本上是JSON的天下了)。rest是一種架構風格,跟編程語言無關,跟平臺無關,RESTFUL特點包括:
1、每一個URI代表1種資源;
2、客戶端使用GET、POST、PUT、DELETE4個表示操作方式的動詞對服務端資源進行操作:GET用來獲取資源,POST用來新建資源(也可以用于更新資源),PUT用來更新資源,DELETE用來刪除資源;
3、通過操作資源的表現形式來操作資源;
4、資源的表現形式是XML或者HTML;
5、客戶端與服務端之間的交互在請求之間是無狀態的,從客戶端到服務端的每個請求都必須包含理解請求所必需的信息
RESTful對url要求非常嚴格,要求每一個URI都表示一個資源。我們看看下面兩個URL:
127.0.0.1/xxx.do?id=1
127.0.0.1/xxx/1
127.0.0.1/xxx/1是屬于RESTful風格的,而127.0.0.1/xxx.do?id=1就不是RESTful風格了。
使用RESTful架構,你的應用結構就變成了下圖所描述的一樣:
注意噢,你的應用更多的是使用JSON數據格式返回數據共其他應用使用,你就是其他應用的數據源!
項目開發引入RESTful架構,利于團隊并行開發。在RESTful架構中,將多數HTTP請求轉移到前端服務器上,降低服務器的負荷,使視圖獲取后端模型失敗也能呈現。但RESTful架構卻不適用于所有的項目,當項目比較小時無需使用RESTful架構,項目變得更加復雜。
接下來我們就開始學習怎樣再Spring MVC中使用RESTFul的架構風格。在這之前我們先了了解下Spring MVC中和RESTFul相關的一個Annotation:
@RequestBody
restful風格的請求數據是使用json格式,此時我們在要接收請求參數的javabean前面添加@RequestBody就可以將請求的數據賦值到相應的bean屬性中。
@GetMapping該注解用來替代RequestMapping,特點是@GetMapping只處理get方式的請求。
@PostMapping該注解用來替代RequestMapping,特點是@PostMapping只處理post方式的請求。
@PutMapping該注解用來替代RequestMapping,特點是@PutMapping只處理put方式的請求。
@DeleteMapping該注解用來替代RequestMapping,特點是@DeleteMapping只處理delete方式的請求。
以上注解就是在restful架構風格中spring mvc常用的注解,下面我們來完成一個restful風格的例子。
前端和后端的數據傳輸都使用json格式了,所以需要引入json相關的依賴之前已經講過了,這里就不多講了。要實現restful風格,還需要修改web.xml文件里面的中央控制器的url匹配方式,不能是*.do之類的了,需要要改成/。
<?xml version="1.0" encoding="UTF-8"?><web-appxmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <filter> <filter-name>characterEncodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>utf-8param-value> init-param> <init-param> <param-name>forceEncodingparam-name> <param-value>trueparam-value> init-param>filter><filter-mapping> <filter-name>characterEncodingFilterfilter-name> <url-pattern>/*url-pattern>filter-mapping> <servlet> <servlet-name>springMVCservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc.xmlparam-value> init-param> <load-on-startup>1load-on-startup>servlet><servlet-mapping> <servlet-name>springMVCservlet-name> <url-pattern>/url-pattern>servlet-mapping> web-app>我們之前將前端控制器的路徑設置為”/”,所有的請求都會通過前端控制器轉發,這樣靜態資源的訪問也會被當作controller的請求,所以我們同樣需要做一些處理。
除了需要在springmvc的配置文件中添加靜態資源,我們還需要設置json格式的字符編碼,否則可能會在響應時出現亂碼。
springMVC使用的StringHttpMessageConverter默認字符編碼是ISO_8859_1,這樣就會導致響應頭中出現Content-Type: text/plain;charset=ISO-8859-1,即使你使用了spring mvc中自帶的編碼過濾器也會出現亂碼問題,因為在字符編碼過濾器中沒有設置響應的Content-Type,所以最好在配置文件中設置json格式的字符編碼為UTF-8。
<?xmlversion ="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"> <beanid="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <propertyname="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8value> <value>application/json;charset=UTF-8value> list> property> bean> <mvc:annotation-driven> <mvc:message-convertersregister-defaults="true"> <bean> <propertyname="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8value> <value>application/jsonvalue> <value>application/xml;charset=UTF-8value> list> property> <propertyname="features"> <list> <value>WriteMapNullValuevalue> <value>WriteNullNumberAsZerovalue> <value>WriteNullListAsEmptyvalue> <value>WriteNullStringAsEmptyvalue> <value>WriteNullBooleanAsFalsevalue> <value>WriteDateUseDateFormatvalue> list> property> bean> mvc:message-converters> mvc:annotation-driven> <mvc:resourcesmapping="/images/**" location="/images/" /> <mvc:resourcesmapping="/js/**" location="/js/" /> <mvc:resourcesmapping="/css/**" location="/css/" /> <mvc:resourcesmapping="/html/**" location="/html/" /> <context:component-scanbase-package="com.pz.web.study.springmvc.*"/> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean> <property name="prefix"value="/jsp/"/> <property name="suffix"value=".jsp"/> bean> beans>本文針對SpringMVC的講解,暫時不需要數據庫方面的操作,因此我們編寫一個DataUtil.java工具類來提供數據支持。下面是rest風格的controller的寫法,一個rest風格的url中是不能包含動詞的(當然你寫動詞了也不會出問題),因為在rest風格眼中,互聯網中的任何一個資源都是一個事物。
package com.pz.web.study.springmvc; import java.time.LocalDate;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set; public class DataUtil { private staticHashMap dataMap = new HashMap<>(); //mock data初始化 static{ User user1 = newUser("pangzi", "13188888888", "北京",LocalDate.of(2010, 10, 10)); User user2 = newUser("matou", "13866666666", "上海",LocalDate.of(2014, 11, 11)); User user3 = newUser("xxxxxx", "13799999999", "廣州",LocalDate.of(2012, 12, 12)); dataMap.put("1", user1); dataMap.put("2", user2); dataMap.put("3", user3); } /** * 查找全部數據 * @return */ public staticHashMapfindAll(){ return dataMap; } /** * 根據id查找用戶 * @param id * @return */ public static UserfindById(String id){ returndataMap.get(id); } /** * 創建用戶 * @param user * @throws Exception */ public static voidcreate(User user) throws Exception{ //遍歷map找到key的最大值 Set> entries = dataMap.entrySet(); Iterator> iterator =entries.iterator(); int max = 3; while(iterator.hasNext()) { Map.Entry next = iterator.next(); int i =Integer.parseInt(next.getKey()); if (i >max) { max = i; } } //將最大值做自增運算,然后作為key放入map中 dataMap.put(++max+"", user); } /** * 更新用戶 * @param id * @param user */ public static voidupdate(String id, User user) throws Exception { dataMap.put(id,user); } /** * 根據id刪除用戶 * @param id * @throws Exception */ public static voiddelete(String id) throws Exception { dataMap.remove(id); }}package com.pz.web.study.springmvc; import com.alibaba.fastjson.JSON;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; @RestControllerpublic class RestFulController { /** * 查找所有用戶 * * @return * @throws Exception */ @GetMapping("/users") public String findAll()throws Exception { HashMap allUser = DataUtil.findAll(); returnJSON.toJSONString(allUser); } /** * 根據id查找 * * @param id * @return * @throws Exception */ @GetMapping("/users/{id}") public StringfindById(@PathVariable String id) throws Exception { User user =DataUtil.findById(id); returnJSON.toJSONString(user); } /** * 新增 * * @param user * @return */ @PostMapping("/users") public Stringcreate(@RequestBody User user) { try { DataUtil.create(user); System.out.println(user.getName()); } catch (Exceptione) { e.printStackTrace(); returnJSON.toJSONString("fail"); } returnJSON.toJSONString("success"); } /** * 更新 * * @param id * @param user * @return */ @PutMapping("/users/{id}") public Stringupdate(@PathVariable String id, @RequestBody User user) { try { DataUtil.update(id, user); } catch (Exceptione) { e.printStackTrace(); returnJSON.toJSONString("fail"); } returnJSON.toJSONString("success"); } /** * 刪除 * * @param id * @return */ @DeleteMapping("/users/{id}") public Stringdelete(@PathVariable String id) { try { DataUtil.delete(id); } catch (Exception e) { e.printStackTrace(); returnJSON.toJSONString("fail"); } returnJSON.toJSONString("success"); }}?? 其實rest風格的前端可以完全不用使用jsp了,關于這一點,在之前的猿進化系列17——實戰之一文學會前后端分離套路中已經討論得淋漓盡致了。
??? 接下來在webapp目錄下創建html文件夾:
??? user_list.html:
??? user_add.html:
<html><head> <metacharset="utf-8"> <metahttp-equiv="X-UA-Compatible" content="IE=edge"> <metaname="viewport" content="width=device-width,initial-scale=1"> <title>新增用戶title> <linkhref="../css/bootstrap.css" rel="stylesheet">head><body><div>div><div> <divid="msg">div> <formid="user-form" style="max-width: 330px;padding: 15px;margin: 0auto;"> <div> <labelfor="name">姓名:label> <inputtype="text" id="name"name="name"> div> <div> <labelfor="phone">手機:label> <inputtype="text" id="phone"name="phone"> div> <div> <labelfor="birthday">生日:label> <inputtype="date" id="birthday"name="birthday"> div> <div> <labelfor="address">地址:label> <input type="text"class="form-control" id="address"name="address"> div> <buttontype="button" class="btn btn-sm btn-primary">添加button> form>div>body><scriptsrc="../js/jquery-3.3.1.min.js">script><script src="../js/bootstrap.js">script><script> $(function () { $(".btn-primary").click(function () { var jsonForm=$('#user-form').serializeArray(); var jsonData ={}; $.each(jsonForm,function (i,v) { jsonData[v.name] = v.value; }); var params =JSON.stringify(jsonData); $.ajax({ url:"/users", type:"post", data:params, dataType:"json", contentType:"application/json", success:function (result) { if(result == "success"){ $(location).attr('href', '/html/user_list.html'); }else{ //提示信息 varmsg = '添加失敗!'; $('#msg').html(msg); setTimeout(function(){ $('#msg').empty(); },2000); } } }); }); });script>html>???? user_update.html:
<html><head> <metacharset="utf-8"> <metahttp-equiv="X-UA-Compatible" content="IE=edge"> <metaname="viewport" content="width=device-width,initial-scale=1"> <title>修改用戶title> <linkhref="../css/bootstrap.css" rel="stylesheet">head><body><div>div><div> <formid="user-form" style="max-width: 330px;padding: 15px;margin: 0auto;"> <inputtype="hidden" id="id"> <div> <labelfor="name">姓名:label> <inputtype="text" id="name"name="name"> div> <div> <labelfor="phone">手機:label> <inputtype="text" id="phone"name="phone"> div> <div> <labelfor="birthday">生日:label> <input type="date"class="form-control" id="birthday"name="birthday"> div> <div> <labelfor="address">地址:label> <inputtype="text" id="address"name="address"> div> <buttontype="button" class="btn btn-sm btn-primary">修改button> form>div>body><scriptsrc="../js/jquery-3.3.1.min.js">script><script src="../js/bootstrap.js">script><script> $(function () { //從url中獲取攜帶的參數 var userId =location.search.split("="); $("#userId").val(userId[1]); //查詢要修改的數據 $.ajax({ url:"/users/"+userId[1], type:"get", dataType:"json", success:function (result) { $("#name").val(result.name); $("#phone").val(result.phone); $("#address").val(result.address); $("#birthday").val(result.birthday); } }); $(".btn-primary").click(function () { var jsonForm=$('#user-form').serializeArray(); var jsonData ={}; $.each(jsonForm,function (i,v) { jsonData[v.name] = v.value; }); var params = JSON.stringify(jsonData); $.ajax({ url:"/users/"+userId[1], type:"put", data:params, dataType:"json", contentType:"application/json", success:function(result) { if(result == "success"){ $(location).attr('href', '/html/user_list.html'); }else{ //提示信息 varmsg = '添加失敗!'; $('#msg').html(msg); setTimeout(function(){ $('#msg').empty(); },2000); } } }); }); });script>html>????? 以上示例就是基于spring mvc的restful架構風格。
我建了一個群,群里有很多高手,歡迎大家入群探討。
總結
以上是生活随笔為你收集整理的restful post请求_猿蜕变9——一文搞定SpringMVC的RESTFul套路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法分析的目的_掌握这些数学函数,你会在
- 下一篇: java连接rabbitmq_没用过消息