Java/Spring

@RequestParam, 커맨드객체

코딩공부 2021. 3. 24. 02:23
private ModelAndView request_TEST(@RequestParam("test") int num,
                                  @RequestParam("test2") String str)){
  //..
}
  • 위처럼 하나이상의 타입을 적용가능. 
  • 스프링에서 지원하는 변환기에서 지원되는 모든 타입을 변환가능
  • RequestParam은 하나 이상의 파라미터 사용가능

ReqeustParam에 넘어오는 데이터가 존재하지 않는다면 BadRequest 400번대 error가 발생함.

 

private ModelAndView request_TEST(@RequestParam(value="test", required=false, defaultValue= "0") int num,
	                              @RequestParam("test2") String str)){
 //..
}
  • required=false로 지정하면 해당 키값이 존재하지 않다고 해서 BadRequest가 발생하지 않음.
  • 존재하지 않다면 num변수에 default로 0이 들어감.

RequestParam을 map에 지정하여 사용

private ModelAndView request_TEST(@RequestParam HashMap<string,string> paramMap)){
    String data = paramMap.get("testParam");
}

 

 

위의 예시처럼 map을 통해서도 파라미터를 컨트롤 할수 있습니다.

대규모의 파라미터를 받는데 map을 사용하기엔 편하지만 유지보수가 어려움.

그래서 커맨드패턴"인 데이터커맨드를 만들서 사용.

 

커맨드객체

 

스프링에서는 이러한 부분을 특정 데이터모델을 만들어 키값과 변수명을 동일하게 한다면 AutoParsing되어 데이터를 손쉽게 사용할수 있는 객체

 

 

1. 컨트롤러에서 다음과 같이 데이터커맨드를 통해 쉽게 적용할수 있다

@RequestMapping("/board/family")
public String boardConfirmId(Family family){
 
    return "board/family";
}

 

2. 데이터 모델을 만듭니다.

@Setter @Getter
public class Family{
	String father;
    String mother;
}​

 

3. jsp화면에서 el 태그로 적용 

 

<h1>
	father : ${family.father}
    mother : ${family.mother}
</h1>

 

 

 

데이터커맨드 alias 주는 방법

@RequestMapping("/board/family")
public String boardConfirmId(@ModelAttribute("fa") Family family){
 
    return "board/family";
}
<h1>
	father : ${fa.father}
    mother : ${fa.mother}
</h1>

 

 

 

 

 

출처 : heavenly-appear.tistory.com/44 heavenly-appear.tistory.com/45

 

 

(Spring) 데이터 커맨드 객체.

웹프로젝트 개발시 Controller에서 RequestParam으로 폼 데이터를 받을 수 있다. 그렇지만 parameter가 많아졌을시 소스상에서 RequestParam으로 명시하면서 모두 나열한다면 소스가 지저분해지고 양도 많아

heavenly-appear.tistory.com

 

(Spring) @ModelAttribute - 데이터커맨드 손쉽게 사용하기 (alias 주기)

지난 포스트에서 데이터 커맨드 객체를 통해서 parameter를 손쉽게 사용할수 있었다. 그런데 데이터커맨드 객체명이 너무 길거다 사용하기 불편할떄 @ModelAttribute를 사용한다면 손쉽게 이용할수 있

heavenly-appear.tistory.com