서블릿과 스프링부트 비교

TopOfTheHead·2025년 10월 18일

Spring

목록 보기
8/16

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{
                    // localhost:8080/hello 로 요청이 수신되는 경우
                    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 MVCController 구현
Spring MVCDispatcher Servlet에서 클라이언트요청 수신 시 요청URLController 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);
    }
}

profile
공부기록 블로그

0개의 댓글