스프링 프레임워크에서는 MVC패턴(Model-View-Controller)을 사용하고 있고, 여기서 Controller는 화면(View)과 비즈니스 로직(Model)을 연결시키는 다리 역할을 한다.
즉, 사용자가 화면에서 입력이나 어떤 요청을 하면 주소를 받아들여 어디로 갈지 분석하고 연결해주는 역할이다.
컨트롤러는 @Controller
어노테이션으로 이 클래스가 컨트롤러인지 파악한다.
이 컨트롤러가 페이지를 찾는 것은 지난번 기본 세팅 시 servlet-context.xml 에 지정해두었으니 자세히 살펴보면 된다.
아래는 기본 컨트롤러의 형식이다.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SampleController {
@RequestMapping("/abcpage")
public String samplePage() {
return "sample";
}
}
>>> 요청주소에 /abcpage를 입력하면 sample.jsp 로 이동하게 된다. (.jsp의 생략도 지난번 구조 세팅할 때 설정해둠 : servlet-context.xml)
↓ 실행결과
위의 SampleController를 보면 알 수 있듯이, 요청 주소와 return 되는 jsp 파일 명은 달라도 이동하는데는 전혀 지장이 없다. 하지만 의미를 두고 정하는 것이 더 좋은 것은 자명하다.👍
요청에 대해 어떤 Controller, 어떤 메소드를 처리할지 맵핑하기 위한 어노테이션이다.
↓ 기본형태
@RequestMapping(value = "/hello", method = RequestMethod.GET)
↓ 예시
@Controller
public class MethodController {
@RequestMapping(value = "/getpage", method = RequestMethod.GET)
public String getpage() {
return "getpage";
}
@RequestMapping(value = "/postpage", method = RequestMethod.POST)
public String postpage() {
return "postpage";
}
}
>>> @RequstMapping은 Class와 Method에 붙일 수 있다. GET, POST, PUT, DELETE
메서드에 대해 각각에 맞는 메서도 옵션이 적용된 어노테이션(@GetMapping, @PostMapping 등
) 이 존재하며, 이를 통해 코드를 간결하게 작성할 수도 있다.
@RequestMapping(value = "/login", method = RequestMethod.GET)
<<< @GetMapping("/login")
Controller 메소드의 파라미터와 웹요청 파라미터를 맵핑하기 위한 어노테이션이다.
↓ 기본 형태
@RequestParam(value="type") String type
↓ 예시
@RequestMapping("/case")
public String paramCase(@RequestParam(value= "type1", required = false) String type1,
@RequestParam(value= "type2", required = false, defaultValue = "") String type2) {
return "param_result";
}
>>> required 가 false이면 파라미터 값이 없을 수도 있다는 것이고, true일 경우 값이 무조건 있어야 한다는 것이다. 또, defaultValue를 사용하기 위해선 required=false
속성을 꼭 명시해주어야 한다.
RequestParam과 헷갈릴 수 있지만, PathVariable은 URL을 처리할 때 사용한다.
ex)/case?type=latte
>>> RequestParam
ex) /case/late
>>> PathVariable
↓ 기본 형태
@RequestMapping("/case/{path1}/{path2}")
public String paramCase4(@PathVariable(name = "path1") String path1,
@PathVariable(name = "path2") String path2) {
return "param_result";
}
Controller 메소드의 파라미터나 리턴값을 Model 객체와 바인딩하기 위한 어노테이션이다.
↓ 기본 형태
@ModelAttribute("SampleItem") SampleDto sampleDto
>>> @ModelAttribute 어노테이션이 붙은 객체가 자동으로 Model 객체에 추가되고 .jsp 뷰단까지 전달 됨.
↓ 예시
@RequestMapping("/return")
public String return7(@ModelAttribute("memberItem") MemberDto memberDto) {
memberDto.setId("modelattribute에 아이디");
memberDto.setPw("modelattribute에 비밀번호");
memberDto.setName("modelattribute에 이름");
return "member_info";
}