JAVA/Spring

@RequestMapping 과 @Controller

호두밥 2022. 1. 26. 20:33

@RequestMapping

@Controller
@RequestMapping("sample")
public class SampleController {
     @RequestMapping("/process")
     public ModelAndView process() {
     return new ModelAndView("view");
     }
}
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)

@RequestMapping이 클래스에 붙은 경우

  • HandlerMapping에서 매핑정보로 인식합니다. 예를 들어 /sample URL로 요청이 오면 SampleController를 호출합니다. 

@RequestMapping이 메소드에 붙은 경우

  • @RequestMapping안에는 URL 정보를 입력해줍니다. URL이 호출되면 해당 URL정보가 등록된 메소드, 즉 @RequestMapping가 명시된 메소드가 호출됩니다. 

@GetMapping,

HTTP GET 방식으로 요청되는 경우 사용합니다. (@RequestMapping(method = { RequestMethod.GET }) 을 간략하게 만든 것입니다.)

@Target({ java.lang.annotation.ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = { RequestMethod.GET })
public @interface GetMapping {
    // abstract codes
}
@GetMapping("/get/{id}")

@PostMapping, @PutMapping, @DeleteMapping, @PatchMapping도 동일하게 사용할 수 있습니다. 각각 HTTP의 POST, PUT, DELETE, PATCH 방식의 요청을 의미합니다. 

@Controller

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}
@Controller
@RequestMapping("sample")
public class SampleController {
     @RequestMapping("/process")
     public ModelAndView process() {
     return new ModelAndView("view");
     }
}

@Controller로 선언하면 스프링 빈으로 등록됩니다. (@Component를 포함하고 있습니다. ) 보통 @RequestMapping과 함께 사용합니다. (@RequestMapping이 없다면 클래스 이름이 일치하는 것을 찾는 방식으로 HandlerMapping이 동작합니다. )

@Controller의 반환 값이 String이면, 뷰 이름으로 인식해, 뷰를 찾고 랜더링 합니다.

@Controller
@RequestMapping("sample")
public class SampleController {
     @RequestMapping("/process")
     public String process() {
     return "view";
     }
}

 

@RestController

RestController는 반환 값으로 view를 찾지 않고 바로 Http Message Body에 입력합니다. REST API를 구현할 때 많이 사용합니다. 

@RestController
@RequestMapping("sample")
public class SampleController {
     @RequestMapping("/process")
     public Sample process() {
     return new Sample();
     }
}

참고자료

김영한, 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술, 인프런

https://www.baeldung.com/spring-new-requestmapping-shortcuts

https://www.baeldung.com/spring-controller-vs-restcontroller

'JAVA > Spring' 카테고리의 다른 글

쓰레드로컬 Thread Local (데이터 경합 방지)  (0) 2023.07.08
Spring MVC 구조  (0) 2022.01.23
스프링 빈과 의존성 주입 (DI)  (0) 2022.01.12