spring后台的controller提供了@RequestParam、@RequestBody等参数注解,使用不同的注解,对于允许的前台请求格式也不一样,下面就列出不同格式的请求实例:
本环境使用spring-boot搭建后台接口服务,前台采用ajax形式发送数据,数据的传递使用Bean实体类接收,在参数接收时,如果出现日期格式无法解析的情况,参见本人的另一篇文章
spring-boot 接口请求之Date、LocalDate、LocalDateTime日期类型转换处理
本文所用的实体Bean为:
public class Ajax implements Serializable{
private Long id;
private String name;
private String path;
private Date createdDate;
private LocalDateTime createdTime;
}第一种:controller参数为不带注解的形式:
后台controller接口:
/***
* 实体类无注解接收参数
* @return
*/
@RequestMapping(value = "/getOfBean")
@ApiOperation("Bean实体参数")
public Ajax getOfBean(Ajax ajax) throws Exception{
logger.info("异步参数接收:{}",ajax.toString());
return ajax;
}ajax请求方式:var param1={
id:1234,
name:'名称',
path:'路径',
createdDate:'2017-01-05 12:45:32',
createdTime:'2017-01-05 12:45:32'
};$.get("http://127.0.0.1:8888/ajaxApi/getOfBean",param, function(result){
console.info("result:"+JSON.stringify(result));
alert(JSON.stringify(result));
});【*】使用无注解的形式接收参数,前台发送json格式数据,使用get和Post方式都可以正常发送、接收数据 第二种:controller使用@RequestBody注解接收参数
后台controller接口:
/***
* 实体类 @RequestBody注解 接收参数
* @param ajax
* @return
* @throws Exception
*/
@RequestMapping(value = "/getOfBeanRequestBody")
@ApiOperation("Bean实体参数@RequestBody注解")
public Ajax getOfBeanRequestBody(@RequestBody Ajax ajax) throws Exception{
logger.info("异步参数接收:{}",ajax.toString());
return ajax;
}ajax请求方式:$.ajax({
type: "post",
url: "http://127.0.0.1:8888/ajaxApi/getOfBeanRequestBody",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.info("result:"+JSON.stringify(result));
alert(JSON.stringify(result));
}
});【*】注意:后台使用@RequestBody朱解释,ajax有如下显示1.必须使用POST方式提交;
2.contentType必须设置为 application/json 格式;
3.发送的参数为json字符串形式,必须使用JSON.stringify(Param) 将json对象转为字符串;
后台controller接口:
/***
* 实体类 @RequestBody注解 接收参数
* @param ajax
* @return
* @throws Exception
*/
@RequestMapping(value = "/getOfBeanRequestParam")
@ApiOperation("Bean实体参数@RequestPatam注解")
public Ajax getOfBeanRequestParam(@RequestParam Ajax ajax) throws Exception{
logger.info("异步参数接收:{}",ajax.toString());
return ajax;
}ajax请求:$.ajax({
type: "post",
url: "http://127.0.0.1:8888/ajaxApi/getOfBeanRequestBody",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.info("result:"+JSON.stringify(result));
alert(JSON.stringify(result));
}
});【*】注意:后台使用@RequestParam注释,和@RequestBody相同,ajax有如下显示
1.必须使用POST方式提交;
2.contentType必须设置为 application/json 格式;
3.发送的参数为json字符串形式,必须使用JSON.stringify(Param) 将json对象转为字符串;
文章为本人测试后所写,欢迎各位留言交流,如有不对请指正,欢迎大家留言
版权声明:本文为xiaoguo1001原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。