Spring MVC之Controller参数接收

@RequestBody 接收参数

注意事项:

  • @RequestBody:后台接收只能声明一个、且只能接收 json
  • @RequestBody:不能和 form/data 共存
  • @RequestBody:必须是:contentType : "application/json;charset=utf-8"

案例:ajax请求

public class RequestBodyPo implements Serializable {

    private Integer id;
    private String name;
    private List<RequestBodyPo> requestBodyPoList;
    private List<RequestBodyPo> BodyPos;

    ... get set 省略...
    
}

请求:

$("#canshu").click(function () {

    var _json = {
        id: "123456",
        name:"asdasdas"
    };
    // 注意观察 requestBodyPoList & BodyPos 命名规范  后台接收数据的时候你会看到效果
    _json.requestBodyPoList = [];
    _json.BodyPos=[];

    var _01 = {id: "1", name: "_01"};
    var _02 = {id: "2", name: "_02"};

    _json.requestBodyPoList.push(_01);
    _json.requestBodyPoList.push(_02);

    _json.BodyPos.push(_01);
    _json.BodyPos.push(_02);

    $.ajax({
        type: "post",
        url: "/requestBody",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(_json),
        success: function (data) {
            console.log(data);
        },
        error: function (jqXHR) {
            alert("发生错误:" + jqXHR.status);
        }
    });
});

controller接收:

上述问题大写开头的字段接收到的参数为何为空呢?

这是由于JavaBean的规范导致的。一般JavaBean属性都是首字母小写,以驼峰命名格式命名,相应的 getter/setter 方法是 get/set 接上首字母大写的属性名。例如:属性名为clientId,其对应的getter/setter 方法是 getClientId/setClientId。

那么如果实际中一定要用首字母大写的字段怎么办呢?我们可以直接在JavaBean的对应字段上加上@JsonProperty注解,如下:

这里的注解是:com.fasterxml.jackson.annotation.JsonProperty。

接收String数组、元素为String的集合 

注意事项:

  • @RequestParam:接收单个字段而非对象实体
  • @RequestParam:使用数组接收可以使用 此注解标识  || @RequestBody 注解,区别前者可以定义多个、后者只能定义一个,并且两者的请求格式不一样

案例:ajax请求

var _json = ["1","2","3"];

$.ajax({
    type: "post",
    url: "/array",
    dataType: "json",
    contentType:"application/x-www-form-urlencoded",//默认值
    data: {
        strings:_json
    },
    success: function (data) {
        console.log(data);
    },
    error: function (jqXHR) {
        alert("发生错误:" + jqXHR.status);
    }
});

controller接收:

上述演示的是 @RequestParam 接收数组、要是 list 直接换成 @RequestParam(value = "lists[]") List<String> lists 即可

如果使用:@RequestBody,则改成 @RequestBody List<String> lists。

再次提醒:使用此注解一定注意请求格式 及 contentType 类型。

接收元素Map的List集合

注意事项:

  • 使用 @RequestBody 方式接收

案例:ajax请求

var _json = [];

var _01 = {
    id: 123,
    name: "小明",
    list: [{
        id: 456,
        name: "翠花"
    }]
};
_json.push(_01);


$.ajax({
    type: "post",
    url: "/listMap",
    dataType: "json",
    contentType: "application/json;charset=utf-8",//默认值  application/x-www-form-urlencoded
    data: JSON.stringify(_json),
    success: function (data) {
        console.log(data);
    },
    error: function (jqXHR) {
        alert("发生错误:" + jqXHR.status);
    }
});

controller接收:

Request 里如何获取 @RequestBody 对应的参数

@RequestBody 用于接收http请求的请求体(request body),在 HttpServletRequest 里是以流的方式传输的。

例如:ajax 发送 POST    "Content-Type":"application/json"

在Controller里(只要能拿到HttpServletRequest的地方就可以),我用fastjson去接收并且转换成java bean,代码如下:

@RequestMapping("/param")
@ResponseBody
public Article param(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    Article article = JSONObject.parseObject(inputStream, Charset.forName("UTF-8"), Article.class);
    return article;
}

@PathVariable

@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值。

@PathVariable("xxx")
//通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“) 
 
@RequestMapping(value=”user/{id}/{name}”)
//请求路径:http://localhost:8080/hello/show5/1/james

 

 其他

@RequestParam:还可以设置 默认参数 和 可选参数  (  @RequestParam(value = "str",defaultValue = "123",required = false) String str  )

controller:还可以接收:

对象实体、List<实体> 等   注意请求格式 contentType

 

posted @ 2022-11-21 22:34  残城碎梦  阅读(489)  评论(0编辑  收藏  举报