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

 

1、httpClient發送Posthtml

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

 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的話在數據處理層要用流來讀取表單屬性,這就是相比傳統表單多的一點內容。代碼下邊已經有了。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 }

 

 

 

2、SpringMVC中post請求參數接收:app

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

      一、@requestBody註解經常使用來處理content-type不是默認的application/x-www-form-urlcoded編碼的內容,好比說:application/json或者是application/xml等。通常狀況下來講經常使用其來處理application/json類型。post

  二、編碼

    經過@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中的屬性名,不然是請求不過去的。url

 三、spa

    在一些特殊狀況@requestBody也能夠用來處理content-type類型爲application/x-www-form-urlcoded的內容,只不過這種方式code

    不是很經常使用,在處理這類請求的時候,@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

相關文章
相關標籤/搜索