Spring MVC configuration file

web.xml file:

The web.xml file contains the entry of DispatcherServlet for handling the requests. Keep the web.xml file in WebContent/WEB-INF directory of your application. Spring framework first initialize the DispatcherServlet and then load the application context from file [servlet-name]-servlet.xml in WebContent/WEB-INF directory.

Example:

  

   
   
      HelloWorld
      
         org.springframework.web.servlet.DispatcherServlet
      
      1
   

   
      HelloWorld
      *.html
   
 

Note: The [servlet-name]-servlet.xml is the default name and WebContent/WEB-INF is the default location for application context file. If we want to use some other name or location we have to inform spring framework by adding ContextLoaderListener in web.xml file.

Example:




....

   contextConfigLocation
   /WEB-INF/HelloWorld-servlet.xml



   
      org.springframework.web.context.ContextLoaderListener
   


[servlet-name]-servlet.xml:

Spring framework loads the application context from [servlet-name]-servlet.xml file. It is used to create or override the beans definitions. The context:component-scan tag is used to activate Spring MVC annotation scanning. The InternalResourceViewResolver is used to define the rules to resolve the view names.

Example:

  


   

   
      
      
   
 

Controller:

A controller is responsible for executing the specific functionality for a request. The @Controller annotation is used define a class as Spring MVC controller. The @RequestMapping annotation is used to map a request URL. A request URL can be mapped to an entire class or a particular method.

Example:

@Controller
public class HelloController {
	   @RequestMapping("/sayHello")  
	   public ModelAndView sayHello() {
	      String message = "Spring MVC Hello World Example.";
	      return new ModelAndView("helloWorld", "message", message);  
	   }
}