Programing_Java

[AJAX] AJAX와 JSON을 이용한 데이터 송수신 처리 방법 본문

Frontend_

[AJAX] AJAX와 JSON을 이용한 데이터 송수신 처리 방법

Joyfullyever 2025. 3. 1. 22:55

✴︎ AJAX (Asynchronous JavaScript and XML)

: 브라우저에서 서버로 비동기 요청을 보내고 응답을 받는 형식

: 페이지를 새로고침하지 않고도 웹 페이지를 동적으로 업데이트 할 수 있게 해주는 기술

: JSON(JavaScript Object Notation)은 데이터를 구조화하여 클라이언트와 서버 간에 데이터를 주고받을 때 사용하는 포맷

1. 서버 측 (Java) - 상품 목록 정렬 API 구현

✴︎ Servlet을 사용한 서버 처리

: 서버 측에선 클라이언트에서 요청한 정렬 조건에 맞춰 데이터베이스에서 상품 목록을 가져온 뒤, 그 데이터를 JSON 형식으로 반환

@WebServlet("/orderProduct")
public class orderProduct extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    public orderProduct() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response); // GET 요청은 POST로 처리
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 클라이언트에서 보낸 정렬 조건을 받음
        String orderCondition = request.getParameter("orderCondition");

        // 조건을 출력해서 확인
        System.out.println("백단 도착 여부 " + orderCondition);

        // 상품 DTO 생성 후 조건 설정
        ProductDTO productDTO = new ProductDTO();
        productDTO.setCondition(orderCondition);

        // DAO 객체를 통해 상품 목록을 가져옴
        ProductDAO productDAO = new ProductDAO();
        ArrayList<ProductDTO> productList = productDAO.selectAll(productDTO);

        // JSON 배열로 변환
        JSONArray productArray = new JSONArray();
        for (ProductDTO product : productList) {
            JSONObject productObj = new JSONObject();
            productObj.put("productnum", product.getProduct_num());
            productObj.put("productname", product.getProduct_name());
            productObj.put("productprice", product.getProduct_price());
            productObj.put("productcnt", product.getProduct_cnt());
            productObj.put("productlike", product.getLiked_cnt());
            productArray.add(productObj);
        }

        // 응답 헤더 설정 (JSON 응답)
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // JSON 데이터 응답으로 반환
        PrintWriter out = response.getWriter();
        out.print(productArray.toString());
        out.flush();
    }
}

 

✴︎ 설명

• Servlet : 클라이언트의 요청을 받아서 처리하고, 결과를 JSON 형식으로 반환하는 서블릿

• productDTO.setCondition(orderCondition) : 클라이언트에서 전달한 정렬 조건을 DTO 객체에 설정

• JSONArray와 JSONObject : Java에서 JSON 배열과 객체를 생성하여 데이터를 구성

• response.setContentType("application/json") : 응답이 JSON 형식임을 명시

 

2. 클라이언트 측 (JavaScript)  - AXJA를 통한 비동기 요청

✴︎ AJXA 요청을 통해 상품 목록 가져오기

function changeProductDatas(value) {
    var orderCondition = value;

    console.log("정렬 조건 : [" + orderCondition + "]");

    $.ajax({
        type: "POST",  // POST 방식 요청
        url: "/shoppingMall/orderProduct",  // 서버 URL
        data: { orderCondition: orderCondition },  // 요청 데이터 (정렬 조건)
        dataType: "json",  // 서버에서 오는 데이터 타입은 JSON
        success: function(response) {
            console.log("상품 정렬 응답 데이터:", response); // 응답 데이터 확인
            
            var boardTable = $("#boardTable");
            boardTable.empty(); // 기존 목록 삭제

            if (response.length > 0) {
                // 응답 데이터가 있을 경우 목록을 생성하여 출력
                $.each(response, function(index, product) {
                    var cnt = (product.productcnt > 0) ? product.productcnt : "품절";  // 재고가 0이면 품절 표시
                    
                    var row = `
                        <li class="list-group-item d-flex justify-content-between align-items-start" 
                            onclick="location.href='controller.jsp?action=PRODUCTDETAILPAGE&product_number=${product.productnum}'">
                            <div class="ms-2 me-auto">
                                <div class="fw-bold">${product.productname}</div>
                                가격 : ${product.productprice}원
                                <br>
                                재고현황 : ${cnt}
                            </div>
                            <span class="badge text-bg-primary rounded-pill">좋아요 ${product.productlike}</span>
                        </li>
                    `;
                    console.log(row);  // 생성된 HTML 확인
                    boardTable.append(row);  // 목록에 추가
                });
            } else {
                boardTable.append('<tr><td>검색 결과가 없습니다!</td></tr>');  // 결과가 없을 경우
            }
        },
        error: function() {
            console.log("에러 발생");  // 요청 실패 시 에러 로그
        }
    });
}

 

✴︎ 설명

• $.ajax : AJAX 요청을 보내는 jQuery 함수. 서버로 요청을 보내고 JSON 응답을 받아 처리

• dataType : "json" : 서버에서 반환되는 데이터가 JSON 형식임을 지정

• success 함수 : 서버에서 응답을 받았을 때 호출되는 함수. 응답 데이터를 이용해 HTML을 동적으로 생성

3. 클라이언트 -서버 간 데이터 흐름

• 클라이언트 : 사용자가 상품 정렬 조건을 선택하고, 이를 서버로 비동기 요청

• 서버 : 서버는 전달받은 정렬 조건을 바탕으로 데이터베이스에서 상품 목록을 가져오고, 결과를 JSON 형식으로 클라이언트에 응답

• 클라이언트 : 서버의 응답을 받아서 HTML을 동적으로 업데이트

4. 결론

✴︎ AJAX와 JSON을 활용하면 페이지를 새로 고침하지 않고도 서버와 데이터를 비동기적으로 주고받을 수 있어, 웹 애플리케이션의 사용자 경험 향상 가능

✴︎ 상품 목록을 정렬하는 기능을 구현하면서, 서버와 클라이언트 간의 데이터 흐름을 알 수 있었음. 공부는 더 해야함...

✴︎ AJAX는 비동기 통신을 가능하게 하여 사용자가 웹 애플리케이션을 사용할 때 더 나은 경험을 제공

✴︎ JSON은 데이터를 쉽게 구조화하여 클라이언트와 서버간에 효율적으로 데이터를 주고받을 수 있도록 도와줌