Set up a maven web project in Intellij with Spring and JPA - Part Six

Hello, welcome to part 6 of these series. Today we will be covering how to configure spring mvc in a web application.

First off all let's configure our web.xml which at this point should look something like this

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">

</web-app>


In a web application you can tell Spring to load config files in the following way: If you would like to pass more config files just separate them with a comma.

    
        contextConfigLocation
        
            /WEB-INF/applicationContext.xml
        
    

    
        org.springframework.web.context.ContextLoaderListener
    

The ContextLoaderListener is responsible for loading the specified config files when your web application is starting.


Only one thing left to do in the web.xml, we need to declare a dispatcherservlet. The dispatcherservlet can be compared to a frontcontroller that will be responsible for mapping the incoming urls to the right jsp pages. I map it to the url pattern '/' because we want it to catch all incoming urls and '/*' seems to be buggy.
 
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            /WEB-INF/dispatcher-servlet.xml
        
        1
    

    
        dispatcher
        /
    


Next thing on the to-do list is adding a xml file called dispatcher-servlet.xml to your WEB-INF folder.
This file will contain instruction for retrieving the right views. Basic configuration should look like this:




Now all we need to configure here is the following
The component scan will tell Spring to look for classes in the Controller package annotated with @Controller.
We will talk more about this in the next tutorial, just remember that the request mappings go in there.
Our InternalResourceViewResolver bean will do the actual mapping to the right jsp page. It will add a prefix and a suffix to what is returned by the controllers and that way it determines which view to serve.
    
    

    
  
  
 


That's all! Next we will look at how to actually implement Spring MVC.


More about this tutorial series can be found here:
Set up a maven web project in Intellij with Spring and JPA - Part One (Project setup)
Set up a maven web project in Intellij with Spring and JPA - Part Two (Maven setup)
Set up a maven web project in Intellij with Spring and JPA - Part Three (ORM mapping)
Set up a maven web project in Intellij with Spring and JPA - Part Four (Spring Configuration)
Set up a maven web project in Intellij with Spring and JPA - Part Five (DAO)
Set up a maven web project in Intellij with Spring and JPA - Part Seven (Implementing Spring MVC)