Spring MVC BeanNameUrlHandlerMapping Example

HandlerMapping is an Interface to be implemented by objects that define a mapping between requests and handler objects. By default DispatcherServlet uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping. In Spring we majorly use the below handler mappings

  1. BeanNameUrlHandlerMapping
  2. ControllerClassNameHandlerMapping
  3. SimpleUrlHandlerMapping

Lets take BeanNameUrlHandlerMapping in this article. Here we will be mapping each request to a Bean directly like below

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
     <bean name="/helloWorld.htm" 
          class="com.javainterviewpoint.HelloWorldController" />
     <bean name="/hello*.htm" 
         class="com.javainterviewpoint.HelloWorldController" />  

Here we can see we have mentioned the Spring container to use BeanNameUrlHandlerMapping and we have mapped each possible request to a controller.

Folder Structure :

  1. Create a Dynamic Web Project “SpringMVCHandlerMappingTutorial” and create a package for our src files com.javainterviewpoint
  2. Place the Spring 3 jar files under WEB-INF/Lib 

    commons-logging-1.1.1.jar
    log4j-1.2.16.jar
    slf4j-api-1.7.5.jar
    slf4j-log4j12-1.7.5.jar
    spring-aspects-3.2.4.RELEASE.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar

  3. Create the Java classes HelloWorldController.java and WelcomeController.java under  com.javainterviewpoint folder.
  4. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  5. View files helloWorld.jsp and welcome.jsp are put under the sub directory under WEB-INF/Jsp

HelloWorldController.java

Our HelloWorldController class extends AbstractController class and overrides “handleRequestInternal()” method. Inside the method we will create a ModelAndView object which has the redirecting page(helloWorld) and user passes a String which will be used at the view page.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController
{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("Inside HelloWorldController");
        ModelAndView model = new ModelAndView("helloWorld");
        model.addObject("msg", "JavaInterviewPoint");
        
        return model;
    }
}

WelcomeController.java

WelcomeController is almost the same as HelloWorldController except the redirecting page and the String passed.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class WelcomeController extends AbstractController
{
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("Inside WelcomeController");

        ModelAndView model = new ModelAndView("welcome");
        model.addObject("msg", "JavaInterviewPoint");
        
        return model;
    }
}

helloWorld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
       <title>Insert title here</title>
    </head>
    <body>
       <h2>Hello World ${msg}</h2> 
    </body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <h2> Welcome to ${msg}</h2>
    </body>
</html>

web.xml

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory. <servlet-name> contains the name of the SpringConfiguration , when the DispatcherServlet is initialized the framework will try to load a configuration file “[servlet-name]-servlet.xml” under the WEB-INF directory.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee%20http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
   <display-name>SpringMVCFormHandling</display-name>
   <welcome-file-list>
       <welcome-file>index.html</welcome-file>
       <welcome-file>index.htm</welcome-file>
       <welcome-file>index.jsp</welcome-file>
       <welcome-file>default.html</welcome-file>
       <welcome-file>default.htm</welcome-file>
       <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
       <servlet-name>SpringConfig</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>SpringConfig</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

SpringConfig-servlet.xml

  • The SpringConfig-servlet.xml is also placed under the WEB-INF directory.
  • Here we have configured BeanNameUrlHandlerMapping as the HandlerMapping
  • Each request is mapped to a Controller as well
<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%20
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd%20
http://www.springframework.org/schema/context%20
http://www.springframework.org/schema/context/spring-context-3.0.xsd%20
http://www.springframework.org/schema/mvc%20
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
 
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/Jsp/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
 
      <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
 
     <bean name="/helloWorld.htm" 
         class="com.javainterviewpoint.HelloWorldController" />
 
     <bean name="/hello*" 
         class="com.javainterviewpoint.HelloWorldController" /> 

     <bean name="/welcome.htm"
         class="com.javainterviewpoint.WelcomeController"/>
 
</beans>

In the above example where ever

  • helloWorld.htm is requested, the DispatcherServlet redirects it to the HelloWorldController.
  • hello123 is requested, the DispatcherServlet redirects it to the HelloWorldController.
  • welcome.htm is requested, the DispatcherServlet redirects it to the WelcomeController.
  • welcome123 is requested, you will get 404 error as there is no mapping for it.

Output

when HelloWorldController called

Hello World JavaInterviewPoint

when WelcomeController called

Welcome to JavaInterviewPoint

Comments

  1. says

    i am learning spring mvc from your site, but while i am run this application i am getting bellow errore ,but there is no red marks in my code,but my code not execute, i am using latest jar files what ever you mention.

    HTTP Status 404 – /SpringMVCHandlerMapping1/

    ——————————————————————————–

    type Status report

    message /SpringMVCHandlerMapping1/

    description The requested resource is not available.

    SEVERE: IOException while saving persisted sessions: java.io.FileNotFoundException: C:\Users\p\Downloads\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\work\Catalina\localhost\Spring_mvc\SESSIONS.ser (The system cannot find the path specified)
    java.io.FileNotFoundException: C:\Users\p\Downloads\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\work\Catalina\localhost\Spring_mvc\SESSIONS.ser (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.(FileOutputStream.java:213)
    at java.io.FileOutputStream.(FileOutputStream.java:101)
    at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:501)
    at org.apache.catalina.session.StandardManager.unload(StandardManager.java:470)
    at org.apache.catalina.session.StandardManager.stop(StandardManager.java:679)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4886)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3458)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1364)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1656)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1665)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1665)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1645)
    at java.lang.Thread.run(Thread.java:745)

    Feb 08, 2016 7:07:07 PM org.apache.catalina.session.StandardManager stop
    SEVERE: Exception unloading sessions to persistent storage
    java.io.FileNotFoundException: C:\Users\p\Downloads\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\work\Catalina\localhost\Spring_mvc\SESSIONS.ser (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.(FileOutputStream.java:213)
    at java.io.FileOutputStream.(FileOutputStream.java:101)
    at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:501)
    at org.apache.catalina.session.StandardManager.unload(StandardManager.java:470)
    at org.apache.catalina.session.StandardManager.stop(StandardManager.java:679)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4886)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3458)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1364)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1656)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1665)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1665)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1645)
    at java.lang.Thread.run(Thread.java:745)

    ——————————————————————————–

    Apache Tomcat/6.0.44

    • javainterviewpoint says

      Venkatesh
      It seems to be a tomcat issue which you used along with eclipse. Try re-installing it and let me know.

Leave a Reply

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