250x250
250x250
JinSeopKim
Hello World!
JinSeopKim
전체 방문자
오늘
어제
  • 분류 전체보기 (168)
    • Artificial intelligence (14)
      • DeepDiveToAI (3)
      • Pytorch (3)
      • Etc (8)
    • Back-end (19)
      • Spring (10)
      • JPA (9)
    • Language (24)
      • Python (3)
      • Java (11)
      • Swift (10)
    • Math (4)
      • Linear Algebra (4)
    • CodingTest (79)
      • Algolithm (12)
      • Backjoon (25)
      • Programmers (42)
    • Etc (27)
      • Book Review (3)
      • Adsp (6)
      • Life (2)
      • Docker (1)
      • odds and ends (15)
    • AI Life (0)
      • 생각 넓히기 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • GitHub

인기 글

태그

  • swift
  • 자바
  • Python
  • JPA
  • 구현
  • 개발자
  • 백준
  • certificate
  • DP
  • ios
  • data
  • AI
  • ADsP
  • 브루트포스
  • Front-end
  • BOJ
  • JAVA8
  • java
  • 코딩테스트
  • 개발
  • 문제풀이
  • BFS
  • uArm
  • 머신러닝
  • SpringMVC
  • 알고리즘
  • 프로그래머스
  • 카카오
  • 선형대수
  • 파이썬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
JinSeopKim

Hello World!

Request Parameter 가져오기
Back-end/Spring

Request Parameter 가져오기

2021. 11. 4. 17:19
728x90
728x90

도입

Spring MVC는 굉장히 편리하게 Request Parameter를 받을수 있다.

과거 Servlet에서는 HttpRequest 객체로부터 getParameter를 받았던 것과 유사하게 받을 수도 있고, 더욱 편리하게 받을 수 도 있다.

이번 포스팅에서는 Servlet에서 Parameter를 받는 것을 시작으로 Spring MVC가 편리하게 받는 방법까지 알아보도록 하겠다.


Request Parameter 받는 방법

1. Servlet처럼 받기

@RequestMapping("/request-param")
    public void requestParam(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}", username);
        log.info("age={}", age);

        response.getWriter().write("ok");
    }

서블릿처럼 HttpServletRequest객체를 받아서 getParameter() 메소드를 호출하여 받을 수 있다.

 

2. @RequestParam annotation 사용하기

    @RequestMapping("/request-param")
    public String requestParam(
            @RequestParam("username") String memberName,
            @RequestParam("age") String memberAge
    ) {
        log.info("username={), age={}", memberName, memberAge);
        return "ok";
    }

@RequestParam의 annotation을 사용하여 받을 수 있다.

memberName에는 username의 데이터가 memberAge에는 age의 데이터가 들어간다.

 

3. @RequestParam의 value값 지우기

    @RequestMapping("/request-param")
    public String requestParam(
            @RequestParam String username,
            @RequestParam String age
    ) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

annoation의  value값을 지울 수 있다. 

제약조건으로는 @RequestParam으로 받는 변수의 이름이 querry parameter로 받는 값과 동일해야한다..

 

4. @RequestParam을 사용하지 않아도 된다.

    @RequestMapping("/request-param")
    public String requestParam(String username, String age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

변수명이 Request Parameter의 이름과 동일하면 annotation을 작성하지 않아도 된다.

 

5. @ModelAttribute 사용하기

    @Data
    public class HelloData {
        private String username;
        private int age;
    }


    @RequestMapping("/model-attribute")
    public String modelAttributeV1(@ModelAttribute HelloData helloData){
        log.info("username={}, age = {}",helloData.getUsername(), helloData.getAge());
        return "ok";
    }

 lombok의 Data annotation을 사용하여 객체로 한번에 받을 수 있다.

일일히 RequestParam을 붙여주는 것을 하지 않아도 된다.

 

6. @ModelAttribute 없애기 가능

    @RequestMapping("/model-attribute")
    public String modelAttribute(HelloData helloData){
        log.info("username={}, age = {}",helloData.getUsername(), helloData.getAge());
        return "ok";
    }

객체가 가지고 있는 값의 이름이 동일하면 @ModelAttribute를 생략 가능합니다.

 

 

그 외 기능

    public String requestParamDefault(
            @RequestParam(required = true, defaultValue = "guest") String username,
            @RequestParam(required = false, defaultValue = "-1") String age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

추가로 @RequestParam의 값중 required와 defaultValue라는것이 있습니다.

required는 default값이 true이고 파라미터를 반드시 받아야 하는지 처리하는 것 입니다.

defaultValue는 파라미터가 request로 넘어오지 않은 경우 default로 넣어줄 값을 의미합니다.

 

이 글은 김영한님의 'Spring MVC 1편' 강의를 공부한 후 작성한 글입니다.
728x90
728x90
저작자표시 비영리 (새창열림)

'Back-end > Spring' 카테고리의 다른 글

SSR Response, Response Body  (0) 2021.11.08
Request Body 받아오기  (0) 2021.11.04
스프링 빈 등록방법과 사용예시  (0) 2021.07.30
Test Case 만들기  (0) 2021.07.28
Static,MVC,API  (0) 2021.07.15
    'Back-end/Spring' 카테고리의 다른 글
    • SSR Response, Response Body
    • Request Body 받아오기
    • 스프링 빈 등록방법과 사용예시
    • Test Case 만들기
    JinSeopKim
    JinSeopKim
    기록📚

    티스토리툴바