DispatcherServlet Spring MVC Example

By Arvind Rai, June 28, 2019
Spring DispatcherServlet is a Servlet. DispatcherServlet receives web request and return response. DispatcherServlet renders the request to spring controller for further processing. DispatcherServlet interacts with View and get the View template and finally returns the response to the client. Spring MVC web flow is given below where front controller is DispatcherServlet.

DispatcherServlet Spring MVC Example

The use of DispatcherServlet is same as any normal servlet. Find the web.xml.

web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app 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"
    version="2.4">
	<display-name>Spring MVC Application</display-name>
	<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>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app> 
In the above web.xml, the dispatcher-servlet.xml is the spring application context.
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans  
   http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package="com.concretepage.controller" />
   
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix" value="/pages/"/>
	  <property name="suffix" value=".jsp"/> 
   </bean>
   
</beans> 
For complete example download source code.

Download Source Code
dispatcherservlet-spring-mvc-example.zip
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us