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

 
 

猜你喜欢

转载自www.cnblogs.com/steve-jiang/p/10000313.html