一、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. 电脑小白和ta的小白电脑——MySQL数据库

    数据库我选择了MySQL,因为据说MySQL是最流行的关系型数据库管理系统,在WEB应用方面 MySQL 是最好的RDBMS之一了,而且,免费呀! MySQL数据库开发环境的配置 (一)下载MySQL ...

  2. 使用Spark进行搜狗日志分析实例——统计每个小时的搜索量

    package sogolog import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  3. CentOS7基本配置一

    CentOS7基本配置一 安装VMwareTools 1.点击重新安装VM-tool, 继而找到压缩文件VMwareTools-10.2.0...tar.gz,复制到桌面下,解压这么压缩文件到桌面下 ...

  4. Problem 2: Even Fibonacci numbers

    Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting w ...

  5. Asp.net APP 重置密码的方式

    在开发ASP.NET WEB APP的时候,时间长了容易忘记最初设置的密码,即使打开数据库也不好重置,因为密码都是加密存储在数据库中的.下面是几种通过代码重置密码的方式: 第一种: string re ...

  6. 酷学习笔记——ASP.NET Core 简介

    ASP.NET Core 简介 其实就是说酷好,不好好学,不学好,没饭吃. 新词汇:IoT,Internet of Things,网联网,微软物联网英文网站.微软物联网中文网站

  7. day13 内置函数一

    见如下网址 https://www.processon.com/mindmap/5bdc3f49e4b0844e0bc6b5d3

  8. SpringCloud 教程

    参考http://blog.csdn.net/forezp/article/details/70148833 出自方志朋的博客

  9. 解决Caused by: java.lang.IllegalArgumentException: A universal match pattern ('/**') is defined before other patterns in the filter chain, causing them to be ignored. Please check the ordering in your

    写项目时应用了SpringSecurity框架来进行登陆验证,之前单独的写简单的SpringSecrity的Demo时并没有报错,但是当和SpringMVC一起整合时却发生了报错 报错如下: Caus ...

  10. C++入门程序作业1

    将一个int A[]={ ,  ,  ,}定义的可能重复的数字去掉重复的元素. 了解向量,容器如何使用,size,地址的关系,理解unique erase函数的返回值是什么参数 结果:将1,1,1,2 ...