Spring MVC hello world XML example

Spring MVC hello world example XML Configuration

Spring MVC hello world XML example

In spring mvc hello world XML example tutorial, I will discuss each and every steps need to perform in order to enable Spring MVC in your project. If you did not setup your environment then I recommend to follow this tutorial Hello World Example in Spring and setup your environment.

It will provide you complete step by step process on how to setup IDE, Maven, Tomcat 7.0 and sample project. When you are done with the initial setup and created a new Maven project as described in above tutorial. We are ready to proceed for the next step.

Step 1 : Setting up environment and project

First thing we need to follow is the directory structure so that we will be on right track. Mismatch in configuration and file path will lead to error in project. So below is the directory structure 


Spring MVC hello world example XML Configuration

 

Step 2 : Defining front controller DispatcherServlet

Next step is to setup DispatcherServlet which is the Front controller in spring mvc framework. DispatcherServlet is the actual servlet which is declared in web.xml of your web application.

You need to provide  servlet mapping to DispatcherServlet, each request coming from that URL will be handled by the DispatcherServlet. In our case, we have defined url mapping to root (“/”), so all the requests will be handled by the DispatcherServlet.

web.xml

<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello World</display-name>

 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/config-servlet.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

ApplicationContext
in spring can be scoped. Each DispatcherServlet has it’s on WebApplicationContext which inherits all beans already defined in root WebApplicationContext.

<web-app>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

Consider the above settings, upon initialization of the web application. The DispatcherServlet will look for the file named dispatcher-servlet.xml (servlet-name-servlet.xml) in your WEB-INF directory.

It will override any bean definition defined in global scope. But in case, you want to specify the location of your context configuration. It can be done by using servlet init parameter contextConfigLocation.

You can specify your bean configuration file as part of your own WebApplicationContext by specifying contextConfigLocation inside your servlet definition. Which will override any bean definition defined in root WebApplicationContext.

<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>

Or you can simply define in root WebApplicationContext as below leaving contextConfigLocation empty value of servlet init-param.

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


Step 3 : Creating application context and view resolver

Next step is to create configuration file. Upon initialization DispatcherServlet will look for the file name provided in contextConfigLocation inside WEB-INF directory or whatever location you have provided.

config-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 <context:component-scan base-package="com.testspring.controllers" />

 <mvc:annotation-driven />

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix">
    <value>/WEB-INF/views/</value>
   </property>
   <property name="suffix">
    <value>.jsp</value>
   </property>
 </bean>

</beans>

We provide application configuration using <beans/> element.

The <beans/> element takes schema name and location as part of it’s attribute which is required in order to validate elements.

The <context:component-scan base-package=”com.testspring.controllers” /> <context:component-scan/> element used to load all component classes annotated with @Component or @Controller. It takes input from it’s attribute base-package as location to the component package.

In our case, com.testspring.controller is the location for all controllers defined using @Controller annotation. <mvc:annotation-driven /> It is used to enable annotation support in web MVC framework. As we are using JSP as part of Spring Web MVC framework, then we will need view resolver that will resolve our view while rendering. There are two different types of view InternalResourceViewResolver which is most commonly used view resolver and alternte you can use ResourceBundleViewResolver.

For ResourceBundleViewResolver, you will have to provide view.properties file which will contain view names and class as below

<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
 <property name="basename" value="views"/>
</bean>

view.properties
#views.properties in WEB-INF/classes :
welcome.(class)=org.springframework.web.servlet.view.JstlView
welcome.url=/WEB-INF/views/home.jsp

InternalResourceViewResolver
can be configured as below
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix">
    <value>/WEB-INF/views/</value>
   </property>
   <property name="suffix">
    <value>.jsp</value>
   </property>
 </bean>


Step 4 : Creating Controller

We can now proceed to create our first controller. You can create controller by simple annotating your class with @Controller annotation as below

HomeController.java
package com.testspring.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
 
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String homePage() {
 return "home";
 }
}
After annotating your class with @Controller, you are now ready to define mapping for the controller. You can map your controller with the help of @RequestMapping annotation so that DispatcherServlet can map request to the mapped controller.

@RequestMapping takes different parameters as required but most commonly and required attributes are value which the URL and method which can be POST, GET, PUT, DELETE etc.

Now create a method which will process the request and return the ModelAndView object. In our case, we are simply returning the view. We are not returning any model object as part of view.

So DispatcherServlet will resolve view name which is “home” and will get it from WEB-INF/views folder and return it to the user.

Step 5 : Output

Next part is to see the output

Spring MVC xml configuration



That’s it 🙂

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *