Java Servlet
。Java를 활용하여 Server-Side에서 Client의 Request와 Response 처리하는 기술
▶ Java의 Servlet Class ( = javax.servlet.http.HttpServlet )를 상속하여 Request와 Response를 처리하는 객체를 Servlet이라고 한다.
。Servlet를 통해 Client에게 요청을 받는 즉시 HTML을 동적으로 생성하여 반환이 가능해짐.
。MVC 디자인패턴의 Controller 역할을 수행
。현재는 Spring MVC의 Dispatcher Sevlet을 통해 받은 모든 요청을 @Controller를 선언한 Controller Class의 @GetMapping 등의 어노테이션으로 라우팅하여 손쉽게 Http Request와 Http Response를 수행하므로 HttpServlet를 사용하지 않는다.
▶ Spring이 요청과 응답을 수행하는 HttpServlet의 기능을 추상화한 계층을 제공
Spring MVC
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);
}
}
