我想將一String組用戶名從 react 傳遞給 Spring,這樣我就可以獲取每個用戶名的一些用戶詳細資訊,最后將其傳回作為回應List<String>
到目前為止,我正在制作一組用戶名,然后將它們作為請求正文傳遞給 spring
const roundRobin = () => {
const userList = []
//Get list of entrants usernames to pass to backend
for(let i = 0; i < entrants.length; i ){
userList.push(entrants[i].username);
console.log(userList);
}
const List = JSON.stringify(userList)
//API call
apiCalls
.getRandomUserList(List)
.then((response) => {
console.log(response.data);
})
.catch((apiError) => {
if (apiError.response.data && apiError.response.data.validationErrors) {
setEditErrors(apiError.response.data.validationErrors);
}
console.log(apiError.response.data)
setPendingApiCall(false);
});
}
在春天,我的控制器將請求正文作為 String[]
//create a random list of members who have entered an event
@CrossOrigin
@GetMapping("/users/createRandomList")
List<String> randomList(@RequestBody String[] usernames) {
return userService.createRandomUserList(usernames);
}
然后 UserService 獲取String[]并將其更改為 List 并呼叫一個隨機重新排列字串順序的方法,然后回圈遍歷回傳的 List(這是一個用戶名)并User從資料庫中獲取并添加有關該用戶的一些詳細資訊到一個新的 List 然后回傳以進行反應。
public List<String> createRandomUserList(String[] randomUsernames) {
List<String> users = new ArrayList<>();
List<String> randomUsersList = Arrays.asList(randomUsernames);
List<String> randomUsers = getRandomUsers(randomUsersList);
for (String randUsernames : randomUsers) {
User u = userRepository.findByUsername(randUsernames);
users.add(u.getFirstname() " " u.getSurname() " " u.getHandicap());
}
return users;
}
//Create list of entrants IDs in random order for tee times.
public List<String> getRandomUsers(List<String> userIds) {
int size = userIds.size();
List<String> passedList = userIds;
List<String> entrants = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < size; i ) {
int randomIndex = rand.nextInt(passedList.size());
entrants.add(passedList.get(randomIndex));
passedList.remove(randomIndex);
}
return entrants;
}
但是,當我嘗試在我的 Web 應用程式中運行它時,出現 HTTP 400 錯誤,
{timestamp: 1640902047907, status: 400, message: 'Required request body is missing: java.util.List<j…ser.UserController.randomList(java.lang.String[])', url: '/api/1.0/users/createRandomList'}
I am not sure what I am doing wrong, as far as I can tell, I am passing an array to Spring, when I console.log(List), I get ["user1","user2"]
uj5u.com熱心網友回復:
我認為您應該將 get 映射更改為 post 映射,然后使用 List 而不是 String[],以這種方式嘗試
@CrossOrigin
@GetMapping("/users/createRandomList")
List<String> randomList(@RequestBody List<String> usernames) {
return userService.createRandomUserList(usernames);
}
也根據變化改變服務方式
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/399182.html
標籤:java arrays reactjs spring-boot
上一篇:Spring分頁僅第一頁有效
