Java 为什么春天又把我变成了一个空虚的人?

Java 为什么春天又把我变成了一个空虚的人?,java,reactjs,spring,spring-boot,Java,Reactjs,Spring,Spring Boot,我似乎不知道为什么Spring会返回一个空列表,因为我已经从reactJS传入了一个JSON.stringify()字符串 这是我为reactJS编写的代码 postData(item){ console.log(item) fetch("http://localhost:8080/addSuspect", { "method": "POST", &qu

我似乎不知道为什么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)
        }

        
    }
postData(项目){
console.log(项目)
取回(“http://localhost:8080/addSuspect", {
“方法”:“发布”,
“标题”:{
“内容类型”:“应用程序/json”
},
“正文”:项目
})
。然后(响应=>{
控制台日志(响应);
})
.catch(错误=>{
控制台日志(err);
});
}
上载文件(事件){
让文件
让我们把文件归档2
//检查是否上传了移动和疑似病例档案
if(event.target.files.length!==2){
this.setState({error:true,errorMsg:“您至少需要上载2个文件!”)
返回
}
//检查文件是否正确
log(“文件:”)
对于(var i=0,l=event.target.files.length;i{
//使用reader.result
const lols=Papa.parse(reader.result,{header:true,skipmptyline:true},)
console.log(lols.data)
//将csv数据发布到数据库中
//this.postData(“”+JSON.stringify(lols.data)+“”)
this.postData(JSON.stringify(lols.data))
//将名称添加到下拉列表中
this.setState({dataList:[“None”,…lols.data.map(names=>names.firstName+“”+names.lastName)])
常量数据=lols.data
this.setState({suspectCases:data})
}
reader.readAsText(文件)
}
}
以下是我从console.log()获得的信息:

[{“id”:“5”,“firstName”:“Bernadene”,“lastName”:“Earey”,“email”:”bearey4@huffingtonpost.com“,”性别“:”女性“,”家庭取向“,”家庭纬度“:”家庭服装“,”家庭邮递代码“:”552209“,”婚姻状况“:”M“,”电话号码“:”92568768“,”公司“:”亚德尔“,”公司名称“:”,”公司取向“:”},{”id“:”14“,”名字“:”玛达“,”姓氏“:”“拉菲”,“电子邮件”:mlafayed@gravatar.com“,”性别“:”女性“,”家庭取向“,”家庭纬度“,”家庭服饰“,”家庭邮资“:”447136“,”婚姻状况“,”M“,”电话号码“:”85769345“,”公司“:”Eare“,”公司取向“:”公司取向“,”

下面显示了我的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);
//        }

    }
}

@RestController
公共类家庭控制器{
私人最终配置文件映射器配置文件映射器;
私人最终怀疑上诉人怀疑上诉人;
公共家庭控制器(@Autowired profileMapper profileMapper,@Autowired suspectedMapper suspectedMapper){
this.profileMapper=profileMapper;
this.suspectedMapper=suspectedMapper;
}
@GetMapping(“/listAllPeopleProfiles”)
//删除CORS错误
@交叉原点(原点=”http://localhost:3000")
私有Iterable getAllPeopleProfiles(){
返回profileMapper.findAllPeopleProfile();
}
@GetMapping(“/listAllSuspectedCases”)
@交叉原点(原点=”http://localhost:3000")
私有Iterable GetAllProspected(){
返回suspectedMapper.findallSuspected();
}
@后映射(“/addSuspect”)
@交叉原点(原点=”http://localhost:3000")
私有void newSuspectedcases(ArrayList未格式化cases){
//试一试{
//最终JSONObject obj=新JSONObject(未格式化案例);
//
//系统输出打印项次(obj);
////ObjectMapper mapper=新的ObjectMapper();
////列表值=mapper.writeValue(obj,可疑的.class);
//}catch(JSONException e){
//e.printStackTrace();
//        }
//
//Gson Gson=新的Gson();
//List suspectedCases=gson.fromJson(unformatedCases,new-TypeToken(){}.getType());
System.out.println(未格式化的案例);
//对于(疑似:疑似病例){
//可疑上诉人添加可疑案件(可疑);
//        }
}
}

我不确定我是否理解你的问题。这是我对你的意思和你希望发生什么的最好猜测:

  • 您希望您的控制器接收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;
    }
[…]
@后映射(“/addSuspect”)
@交叉原点(原点=”http://localhost:3000")
@应答器
私有ArrayList newSuspectedcases(@RequestBody ArrayList UnformatedCases){
[...]
System.out.println(未格式化的案例);
[...]
返回未格式化的案例;
}

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

首先,您的控制器方法返回的是
void
,如果我理解正确,则不是您试图发送的有效负载。您必须使控制器方法返回
List
,才能在响应中接收正文

另一个问题是param上缺少
@RequestBody
注释,该注释告诉Spring从请求中获取主体,并尝试将其反序列化为可疑数组列表

另一个要注意的是,在方法中使用接口而不是实现类作为参数和返回值是一个很好的做法。考虑使用<代码>列表>代码>而不是<代码> ARARYLISTAB/COD> < /P> 所以最后的方法应该是这样的:

   @PostMapping("/addSuspect")
   @CrossOrigin(origins = "http://localhost:3000")
   private List<Suspected> newSuspectedcases(@RequestBody List<Suspected> unformattedcases){
        [...]
        System.out.println(unformattedcases);
        [...]
        return unformattedcases;
    }
@PostMapping(/addSuspect)
@交叉原点(原点=”http://localhost:3000")
private List newSuspectedcases(@RequestBody List unformattedcases){
[...]
System.out.println(未格式化的案例);
[...]
返回未格式化的案例;
}

PS对于CORS问题,您可能希望使用React docs:中所述的本地代理设置,并为远程环境配置CORS,而无需添加localhost:3000。

您的方法newSuspectedcases PostMapping(“/addSuspect”)是v