Servlet 구현
。Spring Bean의 데이터를 활용하여 Spring Boot에 내장된 tomcat의 서버객체를 생성 및 서블릿 컨테이너에 각각의 URL의 요청과 응답을 수행하는 서블릿 객체를 생성 및 추가
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.MediaType;
import java.io.IOException;
class Controller{
public String helloWorld(){
return "hello world";
}
}
@SpringBootApplication
public class ServletPractice {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext();
context.registerBean(Controller.class);
context.refresh();
var webServer = new TomcatServletWebServerFactory()
.getWebServer(servletContext -> {
servletContext.addServlet("frontcontroller", new HttpServlet(){
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException{
if (req.getRequestURI().equals("/hello")) {
var controller = context.getBean(Controller.class);
var result = controller.helloWorld();
resp.setContentType(MediaType.TEXT_PLAIN_VALUE);
resp.getWriter().println(result);
}
}
}).addMapping("/*");
});
webServer.start();
}
}

▶ 브라우저에서 URL로 요청 시 톰캣서버의 서블릿을 통해 응답
Servlet에 대응하는 Spring MVC의 Controller 구현
。Spring MVC의 Dispatcher Servlet에서 클라이언트의 요청 수신 시 요청의 URL에 Controller Class로 라우팅하여 중계
▶ 해당 Controller Class에서 Servlet의 기능을 수행
。Servlet보다 간편한 logic으로 요청과 응답을 수행할 수 있음.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class HelloController{
@GetMapping("/hello")
public String helloWorld(){
return "hello world";
}
}
@SpringBootApplication
public class ServletPractice {
public static void main(String[] args) {
SpringApplication.run(ServletPractice.class, args);
}
}
