본문 바로가기

Java

ajax로 배열 넘기기 / controller에서 arraylist 받기 (@RequestParam)

- ajax 로 배열 넘기기 - 

ajax로 파라미터를 보낼 때 javascript 객체를 하나 보낸다.
그 객체 안에는 여러 가지 key와 value 쌍들이 있고,
그 value 중에는 list 타입도 있다.
이 list를 controller에서 어떻게 받아야 할까?

방법은 두 가지다.
하나는 stringify 해서 문자열로 보내고,
controller에서 parsing하는 방법이다.
parsing 할 때는, 
String을 parsing하여 
그 결과를 JSONArray 로 받고,
그렇게 받은 JSONArray를 그대로 java의 List 변수 안에 넣어준다.

(Java 안에서 JSON을 다루는 법은 아래 글을 참고하자)

https://parksay-dev.tistory.com/49

 


두 번째 방법은 @RequestParam을 쓰는 방법이다.
단, 받을 때 변수명을 잘 맞춰 줘야 한다.

ajax에서 checkedFruitList라는 key에 데이터를 담아서 보냈다면

ex) checkedFruitList : datList
컨트롤러에서 받을 때는 변수명을 "checkedFruitList[]"로 받는다는 점만 주의하면

보통 String이나 int 파라미터들과 똑같다.

- 방법1 -

//javascript - 방법1
let checkedFruitList = [];
    $('tr#fruitCheckRow input').each((index, item) => {
        checkedFruitList.push(item.value);
    });


$.ajax({
    url: 'sendFruit',
    method: 'POST',
    data: {
        fruitName: $('select[name="fruit_name"]').val(),
        fruitColor: $('input[name="color"]').val(),
        checkedFruitList: JSON.stringify(checkedFruitList)	//보내려는 데이터를 문자열로 변환하여 넣기
    },
    success: (result) => {
        console.log(result);
    }
});
//java - 방법1
@RequestMapping(value="sendFruit", method={RequestMethod.POST})
@ResponseBody
public String srr(FruitDTO param) { 
    logger.info(param.getFruitName());
    logger.info(param.getFruitColor());
    logger.info(param.getCheckedFruitList());
}

//파라미터들을 한 번에 받는 DTO 만들어 두기
public class FruitDTO {
    String fruitName;
    String fruitColor;
    ArrayList<Integer> checkedFruitList;
    
	(getter and setter...)    

	//string으로 받은 array를 parsing 하기
    public void setCheckedFruitList(String param) throws ParseException {
        ArrayList<Integer> checkedFruitList = new ArrayList<>();
        JSONParser parser = new JSONParser();
        JSONArray arr =  (JSONArray) parser.parse(param);
        checkedFruitList = arr;
        this.checkedFruitList = checkedFruitList;
    }
}

 

 




- 방법2 -

//javascript - 1
let checkedFruitList = [];
    $('tr#fruitCheckRow input').each((index, item) => {
        checkedFruitList.push(item.value);
    });


$.ajax({
    url: 'sendFruit',
    method: 'POST',
    data: {
        fruitName: $('select[name="fruit_name"]').val(),
        fruitColor: $('input[name="color"]').val(),
        checkedFruitList: checkedPurinfList
    },
    success: (result) => {
        console.log(result);
    }
});



//java - 방법2
@RequestMapping(value="sendFruit", method={RequestMethod.POST})
@ResponseBody
public String srr(String fruitName, String fruitColor, @RequestParam(value="checkedFruitList[]") ArrayList<Integer> checkedFruitList) { 
    logger.info(fruitName);
    logger.info(fruitColor);
    logger.info(checkedFruitList);
}

 

- 220408

반응형