HTTP 요청 파라미터를 조회하는 기능에는 @RequestParam, @ModelAttribute가 있다.
@RequestMapping("/request-param-v1")
public void requestParamV1(HttpServletRequest request, HttpServletResponse
response) throws IOException {
String username = request.getParameter("username");
int age = Integer.parseInt(request.getParameter("age"));
response.getWriter().write("ok");
}
request.getParameter()
로 단순히 HttpServletRequest가 제공하는 방식으로 요청 파라미터를 조회한 모습이다.반면에 스프링이 제공하는 @RequestParam을 사용하면 요청 파라미터를 편리하게 사용할 수 있다.
@ResponseBody
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam("username") String memberName,
@RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName, memberAge);
return "ok";
}
@RequestParam을 사용한 코드이다. 위의 코드를 보면 앞선 코드보다 훨씬 간결해졌음을 알 수 있다.
@RequestParam의 name(value)속성이 파라미터 이름으로 사용된다.
@RequestParam("username") -> request.getParameter("username")
또한, HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParam(name="xx")
을 생략 할 수 있다.
@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(@RequestParam String username, @RequestParam int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
HTTP 파라미터 이름이 변수이름과 같아 생략된 모습이다.
@RequestParam
도 생략가능하다.@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(String username, int age) {
하지만 @RequestParam
이 있으면 명확하게 요청 파리미터에서 데이터를 읽는 다는 것을 알 수 있으므로 선택해서 사용하도록 하자.
@RequestParam.required
를 사용해서 파라미터의 필수 여부를 나타 낼 수 있다.
@RequestParam(required = false, defaultValue = "-1") int age
참고로 defaultValue
는 빈 문자의 경우에도 설정한 기본값이 적용된다.
실제 개발을 하면 요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 아래의 예시처럼 값을 넣어주어야 한다.
@RequestParam String username;
@RequestParam int age;
HelloData data = new HelloData();
data.setUsername(username);
data.setAge(age);
스프링은 위의 과정을 자동화해주는 @ModelAttribute
기능을 제공한다.
스프링 MVC는 @ModelAttribute
가 있으면 다음을 실행한다.
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
직접 setter메서드에 파라미터의 값을 입력하지 않고 @ModelAttribute
를 사용함으로써 자동으로 파라미터의 값을 바인딩 했다.
@ModelAttribute
는 모델(Model)에 @ModelAttribute
로 지정한 객체를 자동으로 넣어준다.@ModelAttribute("hello") Item item //이름을 hello 로 지정
model.addAttribute("hello", item); //모델에 hello 이름으로 저장
@ModelAttribute
는 생략할 수 있다.@RequestParam
도 생략이 가능하고, @ModelAttribute
도 생략이 가능하기에 혼란이 발생할 수 있다.
객체에 getUsername(), setUsername() 메서드가 있으면, 이 객체는 username 이라는 프로퍼티를 가지고 있다. username 프로퍼티의 값을 변경하면 setUsername() 이 호출되고, 조회하면 getUsername() 이 호출된다.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1
김영한님의 스프링 MVC 강의를 수강하면서 작성한 글입니다.
틀린 부분 등 다양한 피드백 환영합니다.