一、httpClient发送Post

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

 public static String httpPostWithJSON(String url) throws Exception {

         HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null; // json方式
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "admin");
jsonParam.put("pass", "123456");
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println(); // 表单方式
// List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
// pairList.add(new BasicNameValuePair("name", "admin"));
// pairList.add(new BasicNameValuePair("pass", "123456"));
// httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); //UrlEncodedFormEntity默认"application/x-www-form-urlencoded" HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he,"UTF-8");
}
return respContent;
} public static void main(String[] args) throws Exception {
String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
System.out.println(result);
}

封装表单属性可以用json也可以用传统的表单,如果是传统表单的话 要注意,也就是在上边代码注释那部分。用这种方式的话在servlet里也就是数据处理层可以通过request.getParameter(”string“)直接获取到属性值。就是相比json这种要简单一点,不过在实际开发中一般都是用json做数据传输的。用json的话有两种选择一个是阿里巴巴的fastjson还有一个就是谷歌的gson。fastjson相比效率比较高,gson适合解析有规律的json数据。博主这里用的是fastjson。还有用json的话在数据处理层要用流来读取表单属性,这就是相比传统表单多的一点内容。代码下边已经有了。

 public class HcServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String acceptjson = "";
User user = new User();
BufferedReader br = new BufferedReader(new InputStreamReader(
(ServletInputStream) request.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
br.close();
acceptjson = sb.toString();
if (acceptjson != "") {
JSONObject jo = JSONObject.parseObject(acceptjson);
user.setUsername(jo.getString("name"));
user.setPassword(jo.getString("pass"));
} request.setAttribute("user", user);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}

二、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

 
 

SpringMVC中post请求参数注解@requestBody使用问题的更多相关文章

  1. springMVC中接收请求参数&&数据转发

    ### 1. 接收请求参数 #### 1.1. [不推荐] 通过HttpServletRequest获取请求参数 假设存在: <form action="handle_login.do ...

  2. Springmvc之接受请求参数二

    Springmvc之接受请求参数 准备工作 新建一个表单提交 请求地址: http://localhost:8080/ProjectName/user/login.do <form action ...

  3. js处理url中的请求参数(编码/解码)

    在处理 a 链接跳转其他页面时,总会遇到需要传递一些当前页面的信息到其他页面,然后其他页面利用这些信息进行相关操作.利用 get 请求或 hash 传递是常见的方式. 首先,需要对传递的参数进行编码, ...

  4. SpringMVC请求参数注解两个小问题

    今天遇到使用SpringMVC请求注解遇到的两个小问题: 如果用@requestBody注解,则请求体内容类型一般要为application/json,如果其类型为multipart/form-dat ...

  5. Spring注解之Controller中获取请求参数及验证使用

    1.处理request的uri部分的参数:@PathVariable. 2.处理request header部分的参数:@RequestHeader,@CookieValue@RequestHeade ...

  6. 学习SpringMVC——如何获取请求参数

    @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@CookieValue)!她(@ModelAndView) ...

  7. Controller中获取输入参数注解使用总结

    1.处理request的uri部分的参数(即restful访问方式):@PathVariable. 当使用restful访问方式时, 即 someUrl/{paramId}, 这时的参数可通过 @Pa ...

  8. 【SpringMVC】获取请求参数

    通过ServletAPI获取 test.html <a th:href="@{/testServletAPI(username='admin',password=123456)}&qu ...

  9. 详解SpringMVC中GET请求

    GET请求概述 GET请求,请求的数据会附加在URL之后,以?分割URL和传输数据,多个参数用&连接.URL的编码格式采用的是ASCII编码,而不是uniclde,所有的非ASCII字符都要编 ...

随机推荐

  1. django中的Q查询

    转载于:https://mozillazg.com/2015/11/django-the-power-of-q-objects-and-how-to-use-q-object.html 原文写的很详细 ...

  2. select、poll、epoll的区别

    本文写于2017-02-26,从老账号迁移到本账号,原文地址:https://www.cnblogs.com/huangweiyang/p/6444746.html select.poll.epoll ...

  3. .net正则匹配

    char[] weixin = txtweixinhao.Text.Trim().ToCharArray(); for (int i = 0; i < weixin.Length; i++) i ...

  4. Ganlia采样、统计及RRD记录周期(频次、间隔)的配置和更改

    Ganglia & RRD Ganglia是伯克利开发的一个集群监控软件.可以监视和显示集群中的节点的各种状态信息,比如如:cpu .mem.硬盘利用率, I/O负载.网络流量情况等,同时可以 ...

  5. Callable抛出异常与future.get

    public class ThreadPoolTest { @Test public void testException(){ try{ testExecutorServiceException() ...

  6. Web应用增加struts2支持

    编辑Web应用的web.xml配置文件,配置Struts2的核心Filter.下面是增加了Struts2的核心 Filter配置的web.xml配置文件的代码片段. <!-- 定义struts2 ...

  7. hdu4003详解(树形dp+多组背包)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4003 Find Metal Mineral Time Limit: 2000/1000 MS (Jav ...

  8. Oracle学习DayThree

    一.视图 1.定义: 视图是一种虚表,是从表中抽出的逻辑上相关的数据集合. 视图建立在已有表的基础上, 视图赖以建立的这些表称为基表. 向视图提供数据内容的语句为 SELECT 语句, 可以将视图理解 ...

  9. 173zrx个人简介

    码云链接:https://gitee.com/zhrx-617/codes/947dbs2fi5kw3jz8hc0ma74 效果图: 源代码: <html> <head> &l ...

  10. ionic3 应用内打开第三方地图导航 百度 高德

    1.安装检测第三方APP是否存在的插件 cordova plugin add cordova-plugin-appavailability --save npm install --save @ion ...