1. 程式人生 > >SpringMVC中post請求引數註解@requestBody使用問題

SpringMVC中post請求引數註解@requestBody使用問題

 

一、httpClient傳送Post

原文https://www.cnblogs.com/Vdiao/p/5339487.html

 1 public static String httpPostWithJSON(String url) throws Exception {
 2 
 3         HttpPost httpPost = new HttpPost(url);
 4         CloseableHttpClient client = HttpClients.createDefault();
 5         String respContent = null
; 6 7 // json方式 8 JSONObject jsonParam = new JSONObject(); 9 jsonParam.put("name", "admin"); 10 jsonParam.put("pass", "123456"); 11 StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解決中文亂碼問題 12 entity.setContentEncoding("UTF-8");
13 entity.setContentType("application/json"); 14 httpPost.setEntity(entity); 15 System.out.println(); 16 17 18 // 表單方式 19 // List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 20 // pairList.add(new BasicNameValuePair("name", "admin"));
21 // pairList.add(new BasicNameValuePair("pass", "123456")); 22 // httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); //UrlEncodedFormEntity預設"application/x-www-form-urlencoded" 23 24 25 HttpResponse resp = client.execute(httpPost); 26 if(resp.getStatusLine().getStatusCode() == 200) { 27 HttpEntity he = resp.getEntity(); 28 respContent = EntityUtils.toString(he,"UTF-8"); 29 } 30 return respContent; 31 } 32 33 34 public static void main(String[] args) throws Exception { 35 String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc"); 36 System.out.println(result); 37 }

 

封裝表單屬性可以用json也可以用傳統的表單,如果是傳統表單的話 要注意,也就是在上邊程式碼註釋那部分。用這種方式的話在servlet裡也就是資料處理層可以通過request.getParameter(”string“)直接獲取到屬性值。就是相比json這種要簡單一點,不過在實際開發中一般都是用json做資料傳輸的。用json的話有兩種選擇一個是阿里巴巴的fastjson還有一個就是谷歌的gson。fastjson相比效率比較高,gson適合解析有規律的json資料。博主這裡用的是fastjson。還有用json的話在資料處理層要用流來讀取表單屬性,這就是相比傳統表單多的一點內容。程式碼下邊已經有了。

 1 public class HcServlet extends HttpServlet {
 2     private static final long serialVersionUID = 1L;
 3        
 4     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 5         doPost(request, response);
 6     }
 7 
 8     
 9     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
10         
11         request.setCharacterEncoding("UTF-8");  
12         response.setContentType("text/html;charset=UTF-8");  
13         String acceptjson = "";  
14         User user = new User();
15         BufferedReader br = new BufferedReader(new InputStreamReader(  
16                 (ServletInputStream) request.getInputStream(), "utf-8"));  
17         StringBuffer sb = new StringBuffer("");  
18         String temp;  
19         while ((temp = br.readLine()) != null) {  
20             sb.append(temp);  
21         }  
22         br.close();  
23         acceptjson = sb.toString();  
24         if (acceptjson != "") {  
25             JSONObject jo = JSONObject.parseObject(acceptjson);
26             user.setUsername(jo.getString("name"));
27             user.setPassword(jo.getString("pass"));
28         }  
29         
30         request.setAttribute("user", user);
31         request.getRequestDispatcher("/message.jsp").forward(request, response);
32     }
33 }

 

 

 

二、SpringMVC中post請求引數接收:

  原文https://www.cnblogs.com/qiankun-site/p/5774300.html

      1、@requestBody註解常用來處理content-type不是預設的application/x-www-form-urlcoded編碼的內容,比如說:application/json或者是application/xml等。一般情況下來說常用其來處理application/json型別。

  2、

    通過@requestBody可以將請求體中的JSON字串繫結到相應的bean上,當然,也可以將其分別繫結到對應的字串上。
    例如說以下情況:
    $.ajax({
        url:"/login",
        type:"POST",
        data:'{"userName":"admin","pwd","admin123"}',
        content-type:"application/json charset=utf-8",
        success:function(data){
          alert("request success ! ");
        }
    });

    @requestMapping("/login")
    public void login(@requestBody String userName,@requestBody String pwd){
      System.out.println(userName+" :"+pwd);
    }
    這種情況是將JSON字串中的兩個變數的值分別賦予了兩個字串,但是呢假如我有一個User類,擁有如下欄位:
      String userName;
      String pwd;
    那麼上述引數可以改為以下形式:@requestBody User user 這種形式會將JSON字串中的值賦予user中對應的屬性上
    需要注意的是,JSON字串中的key必須對應user中的屬性名,否則是請求不過去的。

 3、

    在一些特殊情況@requestBody也可以用來處理content-type型別為application/x-www-form-urlcoded的內容,只不過這種方式

    不是很常用,在處理這類請求的時候,@requestBody會將處理結果放到一個MultiValueMap<String,String>中,這種情況一般在
    特殊情況下才會使用,
    例如jQuery easyUI的datagrid請求資料的時候需要使用到這種方式、小型專案只建立一個POJO類的話也可以使用這種接受方式

接收content-type型別為application/x-www-form-urlcoded的內容 ,可以使用@RequestParam,也可以使用request.getParameter()方式獲取引數。@RequestParam使用request.getParameter()方式獲取引數所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值。參考https://www.cnblogs.com/feiyangyan/p/4958249.html