Spring

체크박스 클릭시 데이터 노출 처리

Stater 2024. 11. 29. 07:33

Controller 구성

import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/example")
public class ExampleController {

    private List<Item> items = List.of(
        new Item(1, "Item 1", 5),
        new Item(2, "Item 2", 0),
        new Item(3, "Item 3", 10)
    );

    @GetMapping("/filter")
    public List<Item> filterItems(@RequestParam boolean showNonZero) {
        if (showNonZero) {
            return items.stream()
                        .filter(item -> item.getNumber() != 0)
                        .collect(Collectors.toList());
        }
        return items;
    }

    static class Item {
        private int id;
        private String name;
        private int number;

        // Constructor, Getters, and Setters
        public Item(int id, String name, int number) {
            this.id = id;
            this.name = name;
            this.number = number;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getNumber() {
            return number;
        }
    }
}


JSP구성

<!DOCTYPE html>
<html>
<head>
    <title>Checkbox Filtering</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#filterCheckbox').change(function () {
                const showNonZero = $(this).is(':checked');
                $.ajax({
                    url: '/example/filter',
                    method: 'GET',
                    data: { showNonZero: showNonZero },
                    success: function (data) {
                        const list = $('#itemList');
                        list.empty();
                        if (data.length > 0) {
                            data.forEach(function (item) {
                                list.append('<li>' + item.name + ' (' + item.number + ')</li>');
                            });
                        } else {
                            list.append('<li>No items to display</li>');
                        }
                    },
                    error: function () {
                        alert('An error occurred while fetching the data.');
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>Item List</h1>
    <label>
        <input type="checkbox" id="filterCheckbox">
        Show only items with non-zero numbers
    </label>
    <ul id="itemList">
        <!-- 초기 데이터를 서버에서 렌더링할 수도 있음 -->
    </ul>
</body>
</html>
반응형

'Spring' 카테고리의 다른 글

체크박스 클릭시 데이터노출 처리 두번째방법  (1) 2024.11.29
스프링 프레임워크  (0) 2020.02.17
JDBC vs MyBatis 차이  (0) 2020.02.05
스프링 특징  (0) 2020.02.03
Spring Security 관련 참고사항  (0) 2019.11.22