Monday, September 11, 2017

Spring MVC : The Framework - Part 2

Spring-MVC Sample


As I described in the previous segment, spring-mvc is a framework that is really useful in developing web-applications. So, to demonstrate the abilities of Spring-MVC lest start with a sample application for library-management-system and understand the building boxes of Spring-MVC

Initializing Project

  1. In this sample project we will use 'Maven' as our dependency management tool. So, initialize a maven-project and add the dependency for 'spring-mvc' in the 'pom' file.
  2. Then Create a directory-structure as follows :


Configurations for Spring-MVC


First of all as I explained in the last chapter we have to map the servlet which our application going to fit. To that we have to create a 'web.xml' file inside 'spring-mvc-sample/src/main/webapp/WEB-INF' directory and add the following configurations to it : 



This configuration will tell the 'DispatcherServlet' to handle the requests coming from the configured URL pattern. After initializing the 'DispatcherSevlet' the frame-work will try to load the 'application-context' from a file named '[servlet-name]-servlet.xml' file which should also be located at 'webapp/WEB-INF' directory by default (to configure this spring-mvc has a mechanism which I will describe in the next chapter).  So, for the application-context to load add a file named 'spring-sample-servlet.xml' into spring-mvc-sample/src/main/webapp/WEB-INF' directory and add the following lines to it.


'context-component-scan' is the place Spring starts searching for the configurations. Usually we will give the 'group-ID' or the 'Base-Package' of our project as base-package. 

The next configuration is for the view-resolver which resolves views when a view-name is given. So, according to this configurations it will resolve views in the path 'WEB-INF/jsp' and with the '.jsp' prefix.

Then add a controller class 'HomeController' inside the 'spring-mvc-sample /src /main /java /com /springmvc /sample /controller' direcotory and add the following lines to it. 


@Controller annotation will tell that this class should be setved as 'Spring-MVC-Controller'. @RequestMapping annotation on top of the 'getHomePage' method will inform Spring where to map the request and according to which HTTP-method.  

And then create a 'home.jsp' file inside 'webapp/WEB-INF' directory and add sample HTML content into it.

And the sample app is done. You can checkout the full-project here














No comments:

Post a Comment