【问题标题】:Why is spring returning me an empty llist?为什么春天给我一个空列表?
【发布时间】:2020-07-29 16:44:47
【问题描述】:

我似乎不知道为什么 Spring 会返回一个空列表,因为我已经从 reactJS 传入了 JSON.stringify() 字符串

这是我的 reactJS 代码

postData(item){

        console.log(item)

        fetch("http://localhost:8080/addSuspect", {
            "method": "POST",
            "headers": {
                "content-type": "application/json"
            },
            "body": item
        })
        .then(response => {
            console.log(response);
        })
        .catch(err => {
            console.log(err);
        });

    }

    uploadFile(event) {
        
        let file
        let file2

        //Check if the movements andsuspected case profiles are uploaded
        if(event.target.files.length !== 2){
            this.setState({error:true, errorMsg:"You need to upload at least 2 files!"})
            return
        }

        //Check if the file is the correct file
        console.log("Files:")
        for (var i=0, l=event.target.files.length; i<l; i++) {
            console.log(event.target.files[i].name);

            if (event.target.files[i].name.includes("_suspected")){
                file = event.target.files[i]
            }
            else if (event.target.files[i].name.includes("_movements")){
                file2 = event.target.files[i]
            }
            else{
                this.setState({error:true, errorMsg:"You have uploaded invalid files! Please rename the files to <filename>_suspected (For suspected cases) or <filename>_movement (For suspected case movement)"})
                return
            }
        }

        //Reads the first file (Suspected profile)
        if (file) {
            const reader = new FileReader();
            reader.onload = () => {
                // Use reader.result
                const lols = Papa.parse(reader.result, {header: true, skipEmptyLines: true}, )
                
                console.log(lols.data)

                // Posting csv data into db
                // this.postData('"' + JSON.stringify(lols.data) + '"')
                this.postData(JSON.stringify(lols.data))

                // Adds names into dropdown
                this.setState({dataList: ["None", ...lols.data.map(names => names.firstName + " " + names.lastName)]})

                const data = lols.data
                this.setState({suspectCases: data})
            }
            reader.readAsText(file)
        }

        
    }

这是我从 console.log() 得到的:

[{"id":"5","firstName":"Bernadene","lastName":"Earey","email":"bearey4@huffingtonpost.com","gender":"Female"," homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"552209","maritalStatus":"M","phoneNumber":"92568768","company":"Yadel ","companyLongtitude":"","companyLatitude":""},{"id":"14","firstName":"Mada","lastName":"Lafaye","email":"mlafayed@gravatar .com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"447136","maritalStatus":"M"," phoneNumber":"85769345","company":"Eare","companyLongtitude":"","companyLatitude":""}]

下面显示了我的 Spring 控制器中的代码

@RestController
public class HomeController {

    private final profileMapper profileMapper;


    private final suspectedMapper suspectedMapper;

    public HomeController(@Autowired profileMapper profileMapper, @Autowired suspectedMapper suspectedMapper) {
        this.profileMapper = profileMapper;
        this.suspectedMapper = suspectedMapper;
    }

    @GetMapping("/listAllPeopleProfiles")
    //Removes the CORS error
    @CrossOrigin(origins = "http://localhost:3000")
    private Iterable<Peopleprofile> getAllPeopleProfiles (){
        return profileMapper.findAllPeopleProfile();
    }

    @GetMapping("/listAllSuspectedCases")
    @CrossOrigin(origins = "http://localhost:3000")
    private Iterable<Suspected> getAllSuspected(){
        return suspectedMapper.findallSuspected();
    }

    @PostMapping("/addSuspect")
    @CrossOrigin(origins = "http://localhost:3000")
    private void newSuspectedcases(ArrayList<Suspected> unformattedcases){

//        try {
//            final JSONObject obj = new JSONObject(unformattedcases);
//
//            System.out.println(obj);
////            ObjectMapper mapper = new ObjectMapper();
////            List<Suspected> value = mapper.writeValue(obj, Suspected.class);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//

//        Gson gson = new Gson();
//        List<Suspected> suspectedCases = gson.fromJson(unformattedcases, new TypeToken<List<Suspected>>(){}.getType());
        System.out.println(unformattedcases);
//        for (Suspected suspected : suspectedCases){
//            suspectedMapper.addSuspectedCase(suspected);
//        }

    }
}

【问题讨论】:

  • 你的方法 newSuspectedcases PostMapping("/addSuspect") 是无效的,它永远不会返回任何东西。
  • 在 Java http 堆栈中,如果您想通过 http 发送响应,您必须打印到可以从 HtypResponse 对象获取的特殊编写器。无法打印到标准输出。但是返回值并让 spring 进行转换通常是一个更好的主意。

标签: java reactjs spring spring-boot


【解决方案1】:

我不确定我是否理解您的问题。这是我对你的意思和你想要发生的事情的最佳猜测:

  • 您希望控制器接收 ArrayList 作为 POST 请求正文
  • 您希望控制器返回 ArrayList 作为 POST 响应正文

如果是这样,试试这个:

[...]
   @PostMapping("/addSuspect")
   @CrossOrigin(origins = "http://localhost:3000")
   @ResponseBody
   private ArrayList<Suspected> newSuspectedcases(@RequestBody ArrayList<Suspected> unformattedcases){
        [...]
        System.out.println(unformattedcases);
        [...]
        return unformattedcases;
    }

如果不是你的意思,请提供更多信息。

【讨论】:

    【解决方案2】:

    首先,您的控制器方法返回 void 而不是,如果我没有正确理解,您正在尝试发送的有效负载。您必须让控制器方法返回 List&lt;Suspected&gt; 才能在响应中接收正文。

    另一个问题是您在参数上缺少 @RequestBody 注释,它告诉 Spring 从请求中获取正文并尝试将其反序列化为可疑对象的 ArrayList。

    另外需要注意的是,在方法中使用接口而不是实现类作为参数和返回值是一种很好的做法。考虑使用List&lt;Suspected&gt; 而不是ArrayList&lt;Suspected&gt;

    所以最终的方法应该是这样的:

       @PostMapping("/addSuspect")
       @CrossOrigin(origins = "http://localhost:3000")
       private List<Suspected> newSuspectedcases(@RequestBody List<Suspected> unformattedcases){
            [...]
            System.out.println(unformattedcases);
            [...]
            return unformattedcases;
        }
    

    PS 对于 CORS 问题,您可能希望使用 React 文档中所述的本地代理设置:https://create-react-app.dev/docs/proxying-api-requests-in-development/ 并为远程环境配置 CORS,而不添加 localhost:3000。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多