Several ways of receiving arrays in Java back-end

The first

  • The front end converts the parameters to JSON type

 Front-end code:

$.ajax({
       type: "post",
       url: baseUrl + "/stock/detail",//对应controller的URL
       async: true,
       dataType: 'json',
       contentType : "application/json",
       data: JSON.stringify(ids),//json对象转化为json字符串
       success: function (ret) {
          console.log(ret);
       }

 Backend code:

@RequestMapping(value = "/detail")
@ResponseBody
public String detail(HttpServletRequest req,@RequestBody String[] ids) {
    if (!StringUtils.isEmpty(ids))
       for (int i = 0; i < ids.length; i++) {
           String idsss = ids[i];
           System.out.println("requestBody获取传递的json数组参数:" + id);
       }
     }else{
        System.out.println("requestBody获取传递的json数组参数为空");
     }

The second

  • Front-end js passes json string, set contentType: "application/json"

 Front-end code:

        var dataObj = {
            "ids":ids
        }
        var dataJsonStr = JSON.stringify(dataObj);
        $.ajax({
            type:"post",
            url:baseUrl+"/stock/detail",//对应controller的URL
            async:true,
            contentType : "application/json",
            dataType: 'json',
            data: dataJsonStr,
            success:function(ret){}

Backend code:

    @RequestMapping(value = "/detail",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> detail(@RequestBody TStockInventoryDetail detail){//

The third

  • No processing of front-end parameters 

Front-end code:

        var ids = new Array();
        ids.push(1);
        $.ajax({
            type: "post",
            url: baseUrl + "/stock/detail.json",//对应controller的URL
            async: true,
            dataType: 'json',
            data: {
                "array": ids
            },
            success:function(d){
            }

Backend code:

String[] array = req.getParameterValues("array[]");
if (!StringUtils.isEmpty(array)){
   for (String string : array) {
       System.out.println("直接获取传递的数组参数:"+string);
    }
}else{
   System.out.println("直接获取传递的数组参数为空");
}

 

Guess you like

Origin blog.csdn.net/qq_43037478/article/details/114967769