Spring MVCMake the following changes to the Maven web application we created in the previous step: 1. Add the dependency org.springframework:spring-webmvc:4.3.5.RELEASE 2. Add the following to web.xml:
This specifies a Spring servlet DispatcherServlet which will be loaded when the web application is started (notice the <load-on-startup>), and this servlet is responsible for initializing the Spring servlet context, i.e. creating all the beans specified in a bean configuration file. The default name for the bean configuration file is <dispatcher-servlet-name>-servlet.xml under the WEB-INF folder. In our case, the name of the DispatcherServlet is springmvc (notice the <servlet-name>) so the bean configuration file is springmvc-servlet.xml. During operation DispatcherServlet also serves as the front controller that dispatches requests to the proper controller based on controller URL mapping. 3. Create the Spring bean configuration file springmvc-servlet.xml under WEB-INF as follows:
<mvc:annotation-driven /> enables request dispatching to @Controllers among some other things. <context:component-scan> finds all the annotated beans in springmvc.web and its sub-packages. The InternalResourceViewResolver maps a view name to a JSP file. It has two properties: prefix and suffix, so a view name like "home" would be mapped to a JSP file /WEB-INF/jsp/home.jsp. And this is pretty much it - your web application is now a Spring MVC application. You can create a controller and a view like the following: And after that you can run the project and check if it works at the URL http://localhost:8080/springmvc/ or http://localhost:8080/springmvc/index.html. |