ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring - @ModelAttribute, @RequestParam 파헤치기
    Spring 2025. 6. 26. 17:00
    반응형

    ✅ 1. HttpServletRequest로 직접 파라미터 추출

    • 설명: 서블릿 방식으로 HttpServletRequest에서 직접 값을 추출하는 기본 예시입니다.
    • URL: /param/manual
    @RequestMapping("/param/manual")
    public void handleManual(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}, age={}", username, age);
        response.getWriter().write("ok");
    }

    ✅ 2. @RequestParam 사용 (명시적 방식)

    • 설명: @RequestParam("key")를 통해 요청 파라미터 값을 명시적으로 바인딩합니다.
    • URL: /param/explicit
    @ResponseBody
    @RequestMapping("/param/explicit")
    public String handleExplicit(
            @RequestParam("username") String username,
            @RequestParam("age") int memberAge) {
    
        log.info("username={}, age={}", username, memberAge);
        return "ok";
    }

    ✅ 3. @RequestParam 생략 (이름이 일치할 때만)

    • 설명: 파라미터 이름과 변수명이 일치하면 @RequestParam의 name 속성 생략이 가능합니다.
    • URL: /param/implicit
    @ResponseBody
    @RequestMapping("/param/implicit")
    public String handleImplicit(
            @RequestParam String username,
            @RequestParam int age) {
    
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    ✅ 4. @RequestParam 완전 생략

    • 설명: 단순 타입(String, int 등)이며 변수명이 파라미터명과 같을 경우 @RequestParam도 생략 가능합니다.
    • URL: /param/naked
    @ResponseBody
    @RequestMapping("/param/naked")
    public String handleNoAnnotation(String username, int age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    ⚠️ 5. 필수 파라미터 설정

    • 설명: @RequestParam(required = true)로 필수 여부를 지정할 수 있습니다. (기본값은 true)
    • URL: /param/required
    @ResponseBody
    @RequestMapping("/param/required")
    public String handleRequired(
            @RequestParam(required = false) String username,
            @RequestParam(required = true) int age) {
    
        log.info("username={}, age={}", username, age);
        return "ok";
    }​

    ✅ 6. 기본값 설정 (defaultValue)

    • 설명: 값이 누락되거나 빈 문자열일 때 기본값을 지정할 수 있습니다.
    • URL: /param/default
    @ResponseBody
    @RequestMapping("/param/default")
    public String handleDefault(
            @RequestParam(required = false, defaultValue = "guest") String username,
            @RequestParam(required = false, defaultValue = "1") int age) {
    
        log.info("username={}, age={}", username, age);
        return "ok";
    }

     


    ✅ 7. 전체 파라미터를 Map으로 받기

    • 설명: @RequestParam Map을 사용하면 파라미터 전체를 Map 형태로 받을 수 있습니다.
    • URL: /param/map
    @ResponseBody
    @RequestMapping("/param/map")
    public String handleMap(@RequestParam Map<String, Object> paramMap) {
        log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));
        return "ok";
    }

    ✅ 8. 객체로 파라미터 바인딩 (@ModelAttribute 명시적 사용)

    • 설명: 요청 파라미터를 객체에 바인딩해주는 전형적인 @ModelAttribute 사용법입니다.
    • URL: /param/model-explicit
    @ResponseBody
    @RequestMapping("/param/model-explicit")
    public String handleModelExplicit(@ModelAttribute HelloData helloData) {
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        return "ok";
    }

    ✅ 9. 객체로 파라미터 바인딩 (@ModelAttribute 생략)

    • 설명: 생략해도 내부적으로 @ModelAttribute가 적용됩니다. 필드명이 파라미터명과 일치해야 합니다.
    • URL: /param/model-implicit
    @ResponseBody
    @RequestMapping("/param/model-implicit")
    public String handleModelImplicit(HelloData helloData) {
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        return "ok";
    }

     

     

    📌 참고 요약

    방식 설명 어노테이션 특징
    HttpServletRequest 서블릿 방식 직접 접근 없음 비추천 (구식 방식)
    @RequestParam 단일 값 바인딩 사용함 간편하지만 단순 타입에 적합
    @ModelAttribute 객체 바인딩 사용 또는 생략 가능 객체 필드와 파라미터명이 일치해야 자동 매핑됨
    @RequestParam Map 전체 파라미터 받기 사용함 Key-Value 형태로 다이내믹하게 처리 가능
    반응형

    댓글

Designed by Tistory.