교육 (Today I Learned)/Hanaro

[Hanaro] 57일차 / Spring Boot (URI 어노테이션)

Bay Im 2024. 4. 6. 12:38

연습문제 풀이

URI 어노테이션 2가지 (경로 설정)

  • @RequestParam
    • URI 형식
      • localhost:8080/update-form?index=1
    • 메서드 구현
      •     // 관리자 페이지 - 회원목록 상세 출력
            // localhost:8080/update-form?index=1
            @GetMapping("/update-form")
            public String viewUpdateForm(@RequestParam int index, Model model) {
                model.addAttribute("index", index);
        
                Member member = memberList.get(index-1);
                model.addAttribute("member", member);
                return "update-form";
            }
    • html에서 경로이동 설정
      • th:href="@{/update-form(index=${status.count})}”
  • @PathVariable
    • URI 형식
      • localhost:8080/update-form/1
    • 메서드 구현
      •     // 관리자 페이지 - 회원목록 상세 출력
            // localhost:8080/update-form/1
            @GetMapping("/update-form/{index}")
            public String viewUpdateForm(@PathVariable int index, Model model) {
                model.addAttribute("index", index);
        
                Member member = memberList.get(index-1);
                model.addAttribute("member", member);
                return "update-form";
            }
    • html에서 경로이동 설정
      • th:href="@{/update-form/{index}(index=${status.count})}"
  • 두 방법의 차이
    • @PathVariable은 값을 하나만 받아올 수 있다.
    • 여러 개의 데이터를 받아올 때는 @RequestParam을 사용한다.
    • @RequestParam은 URI 외에도 ajax 요청을 통한 데이터를 받아올 수 있다. (Model 사용시 데이터 가져올 때)
    • 보안이 필요한 회원가입 같은 작업을 할 때는 @RequestParam을 사용한다.
728x90