티스토리 뷰

servlet 3.0이 되면서 예전에 web.xml에서 하던 servlet에 대한 설정을 java config로 할 수 있다. 기본적으로는 이런 servlet에 대한 설정을 안해주면 springboot가 DispatcherServlet으로 처리를 한다. 하지만 때에 따라 다른 servlet을 태워야 하는 요청이 있을수도 있다. 이것을 하기 위한 방법은 다음과 같다. 

Application.java (springboot main class)

@SpringBootApplication
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ApiApplication.class);
        application.run(args);
    }
    
    @Bean
    public ServletRegistrationBean fooServletRegistrationBean(){
        return new ServletRegistrationBean(new FooServlet(), "/foo/*");
    }
    
    @Bean
    public ServletRegistrationBean barServletRegistrationBean(){
        return new ServletRegistrationBean(new BarServlet(), "/bar/*");
    }
}

이렇게 ServletRegistrationBean을 이용하여 servlet을 추가할 수 있다. 여기는 기술을 안했지만 init-param이라던지 loadOnStartup, order 등등의 옵션을 ServletRegistrationBean를 통해 설정할 수 있다. servlet을 여러개 추가하고 싶으면 ServletRegistrationBean bean을 여러개 만들어서 등록을 해주면 된다. (물론 bean 이름은 다르게 생성)

FooServlet, BarServlet은 그냥 Test를 위해 만든 Servlet이다.

 

FooSerlvet.java

public class FooServlet extends HttpServlet {
   
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 
        response.getWriter().print("oing");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { 
        response.getWriter().print("daddy");
    }
}

servlet 추가 테스트를 위해 위와 같이 만들어봤다. BarServlet도 이와 유사하므로 생략하겠다. 

 

위와 같이 구성을 하면 /foo/* 에 대한 요청은 FooSerlvet이 처리를 하고 /bar/* 에 대한 요청은 BarServlet, 나머지 모든 요청은 spring의 DispatcherServlet이 처리를 한다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31