I am trying to understand Spring MVC in more detail what I currently know. I am referring to online tutorials and books. As I understand, Spring MVC framework has "Front controller" and "MVC" design patterns.
The front controller (DispatcherServlet) uses the HandlerMapping for mapping URL to the controller classes. I am not using annotations because I want to understand what the framework does behind the scenes.
In this quest, I created a simple web-application based on Spring MVC, the code is below:
Controller code:
public class SimpleSpringController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception {
ModelAndView mw = new ModelAndView("welcome","welcomeMessage", "welcome user!");
return mw;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>FirstSpringMVCProject</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Spring xml configuration
<beans>
<bean id="HandlerMapping1" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/welcome" class="com.example.controller.SimpleSpringController"/>
<bean id="viewResolver1" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/</value> </property>
<property name="suffix"> <value>.jsp</value> </property>
</bean>
</beans>
The application works as expected.
The concepts which I am not able to understand is on the spring configuration xml where we specify the HandlerMapping and ViewResolver implementations.
For example, we have the following bean definition in the above spring xml configuration:
<bean id="HandlerMapping1" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
In above xml config, org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping is one of the implementations of the HandlerMapping interface.
The bean id for this is HandlerMapping1, which is just a random identifier ( I could have very well chosen MyHandlerMapping). The following are the doubts:
Who reads this configuration file? Do front controller read this configuration file?
How does the framework knows that the id of
HandlerMappingimplementation in above case isHandlerMapping1. Usually we do getBean("beanId"), where we specifically know what a particular bean id is. How come spring framework is automatically infer that this is the implementation class ofHandlerMapping.
Any inputs to understand this would be of great help.
