diff --git a/springboot/server/build.gradle b/springboot/server/build.gradle index f5859375..9c7c1260 100644 --- a/springboot/server/build.gradle +++ b/springboot/server/build.gradle @@ -14,6 +14,9 @@ repositories { dependencies { //서블릿 implementation 'jakarta.servlet:jakarta.servlet-api:6.0.0' + + // 스프링 MVC + implementation 'org.springframework:spring-webmvc:6.0.4' } tasks.named('test') { diff --git a/springboot/server/src/main/java/hello/container/AppInitV2Spring.java b/springboot/server/src/main/java/hello/container/AppInitV2Spring.java new file mode 100644 index 00000000..48ec3d50 --- /dev/null +++ b/springboot/server/src/main/java/hello/container/AppInitV2Spring.java @@ -0,0 +1,27 @@ +package hello.container; + +import hello.spring.HelloConfig; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletRegistration; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class AppInitV2Spring implements AppInit { + @Override + public void onStartup(ServletContext servletContext) { + System.out.println("AppInitV2Spring.onStartup"); + + // 스프링 컨테이너 생성 + AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); + appContext.register(HelloConfig.class); + + // 스프링 MVC 디스패처 서블릿 생성, 스프링 컨테이너 연결 + DispatcherServlet dispatcher = new DispatcherServlet(appContext); + + // 디스패처 서블릿을 서블릿 컨테이너에 등록 + ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcherV2", dispatcher); + + // /spring/* 요청이 디스패처 서블릿을 통하도록 설정 + servlet.addMapping("/spring/*"); + } +} diff --git a/springboot/server/src/main/java/hello/spring/HelloConfig.java b/springboot/server/src/main/java/hello/spring/HelloConfig.java new file mode 100644 index 00000000..9f8b2204 --- /dev/null +++ b/springboot/server/src/main/java/hello/spring/HelloConfig.java @@ -0,0 +1,13 @@ +package hello.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class HelloConfig { + + @Bean + public HelloController helloController() { + return new HelloController(); + } +} diff --git a/springboot/server/src/main/java/hello/spring/HelloController.java b/springboot/server/src/main/java/hello/spring/HelloController.java new file mode 100644 index 00000000..0cdc9a03 --- /dev/null +++ b/springboot/server/src/main/java/hello/spring/HelloController.java @@ -0,0 +1,14 @@ +package hello.spring; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloController { + + @GetMapping("/hello-spring") + public String hello() { + System.out.println("HelloController.hello"); + return "hello spring!"; + } +}