DispatcherServlet and tomcat


#1

Marco, can you explain a little more about the interaction between spring boot’s DispatcherServlet (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html) and tomcat?

How (where?) is DispatcherServlet injected (?) into tomcat or where/how does tomcat make use of DispatcherServlet?

Thanks!


#2

To continue my answer from the other thread.

All that Tomcat can do (that’s a complete oversimplification, but will do for now) is run servlets and filters. I.e. servlets that you wrote.

Now in Spring/Spring Boot you tend to annotate your controller classes with @Controller/@RestController and then give them specific path mappings like @GetMapping("/helloWorld").

But Tomcat doesn’t care nor know anything about these controllers or anything spring related.

It can only run “servlets”. I.e. it needs a servlet that check’s the currently requested URL, like /helloWorld, and then KNOW that it should probably call some @Controller annotated class, with the respective @GetMapping.

And that’s Spring’s DispatcherServlet. It is THE glue between Tomcat’s world and Spring’s World. DispatcherServlet will make sure to boot up your applicationcontext and then map between URLs and Spring Code.