Spring MVC – DispatcherServlet Example

SHARE & COMMENT :

DispatcherServlet Configuration

DispatcherServlet : In Spring’s web MVC framework the mechanism of dispatching the request to the appropriate controllers is achieved by configuring the DispatcherServlet class. DispatcherServlet is the class which manages the entire request handling process.Like a normal servlet DispatcherServlet also needs to be configured in the web deployement Descriptor(web.xml).By default DispatcherServlet will look for a name dispatcher-servlet.xml to load the Spring MVC configuration. Spring’s DispatcherServlet is completly integrated with the Spring ApplicationContext and enables to use all the other features of the Spring.This example will explain about DispatcherServlet and its configuration.

Spring Framework Articles

also read:

Spring MVC DispatcherServlet example

1.Modify the web.xml to configure the DispatcherServlet.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--Here we specify about the DispatcherServlet class in the Web Deployment Descriptor-->
	<servlet>
        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

2.Create an dispatcher-servlet.xml file which contains all the configuration beans to handle the user requests.It handles the user request and dispatches to respective controllers.

The basic usage of the dispatcher-servlet.xml

  • Spring’s MVC Inversion of Control is configured in dispatcher-servlet.xml file.
  • Any dependency Injection for the beans is also configured in the dispatcher-servlet.xml like ConstructorInjection,SetterInjection,InterfaceInjection.
  • Spring MVC provides a feature to initialize and inject the dependencies from the dispatcher-servlet.xml
  • ViewResolvers are also configured in dispatcher-servlet.xml
  • Predefined tags supported by Spring Framework makes easier for the user to initialize the beans.

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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
      <property name="urlMap">
<map>
<entry  key="/index.html">
<ref bean="student"/>
</entry>
</map>
</property>

 </bean>

 <bean id="student" class="Student">
             <constructor-arg index="0" type="java.lang.String" value="Ganesh"/>
             <constructor-arg index="1" type="int" value="20"/>
             <constructor-arg index="2" type="java.lang.String" value="Computer Science"/>

          </bean>

     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

3.Create a Jsp file index.jsp to display the output.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>
    </head>

   <body bgcolor="#DDDDDD">
<h2>Spring MVC DispatcherServlet Example</h2>
        <table align="center" style="font-weight:bold;">
            <tr>
                <td>Student Name </td>
                <td>${name}</td>
            </tr>
            <tr>
                <td>Age </td>
                <td>${age}</td>
            </tr>
            <tr>
                <td>Branch </td>
                <td>${branch}</td>
            </tr>

        </table>

    </body>
</html>

4. Create a Java class file Student.java which extends AbstractController and contains three fields (name,age and branch) which will be injected from the Spring IOC using the constructor. Here this class acts like a controller.

Student.java

public class Student extends AbstractController

{

    private String name;
    private int age;
    private String branch;

    public Student() {

    }

    public Student(String name, int age, String branch)  {
        this.name = name;
        this.age = age;
        this.branch = branch;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {

         ModelAndView mv=new ModelAndView();

        mv.addObject("name",getName());
        mv.addObject("age", getAge());
        mv.addObject("branch", getBranch());
        return mv;

    }

   }

5.Building and running the application

also read:

Output

Access page:http://localhost:8080/DispatcherServlet/index.htm

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better