contentType: 指明发送的data数据(这里是aa)的类型
参数值:application/x-www-form-urlencoded
(默认)
特点: 以key/value为一组使用&连接,如:username=lly&password=123,get请求的时候将它放到url上,post请求的时候将它放到请求体中。
接收方式:
- 原生Servlet使用
request.getParameter(“user”)
的这种形式即可获取参数 - spring mvc框架可
自动根据参数名进行匹配
,即表单元素的name属性和接收参数的名称一样时即可自动匹配;如果不一样,可以使用@RequestParam
的方式匹配。
//http请求:
POST http://localhost:8080/springmvc_annotation/user2/add
Content-Type: application/x-www-form-urlencoded
username=李连芸//springmvc controller:
addUser(@RequestParam("username") String name) //key和param不匹配
addUser1(String username, String password) //key和param匹配
addUser2(User user) //key和class的属性匹配
参数值:application/json
特点:
接收方式:
- 原生的Servlet中可以使用
request.getParameterMap()
来获取。(注意,只能获取Get方式传入的数据。post传入的需要使用输入流的方式来读取。)或者使用fastjson,服务器与客户端之间用字符串的方式传递json数据,用的时候各自解析。 - 在spring mvc中通过
@RequestBody
来解析并绑定json字符串参数到方法入参。
@RequestBody 注解详解 作用:
1)该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
//http请求
var aa = {"username":"llyppppppost","password":"33333333"}
$.ajax({type:"POST",url:"http://localhost:8080/springmvc_annotation/user3/add",contentType:"application/json", //发送的data类型dataType:"json", //接受的data类型data:JSON.stringify(aa),success:function(data){console.log("post--------")console.log(data)}
});
//springmvc controller:
//@RequestMapping(value = "/add",method = RequestMethod.POST) //等同于PostMapping方式
@PostMapping("/add")
@ResponseBody
public R addUser(@RequestBody User user){System.out.println("post "+user);return R.success(); //R是包含code,message的自定义返回类
}