Spring 4 MVC Hello World Class Name Handler Mapping Example

July 10, 2015 | Updated last October, 2015 | 1610 views | Comments

Create a Spring WebMVC 4 Hello World app using the Class ControllerClassNameHandlerMapping. Home page, About Page, and Contact Page will be demonstrated in this example.

 

Built and tested with the following:

  • Eclipse Juno IDE
  • Apache Tomcat 7.0.47
  • JDK 1.7.0
  • Maven 3.0.4
  • Spring Web-MVC Framework 4.2.2
    • Configuration: XML
    • Url Mapping: Class Name Handler

 

Step 1. Create a new Maven Project.

Set up a new Maven Project with the following details:

  • Group Id: com.consistentcoder
  • Artifact Id: spring-4-mvc-hello-world-class-name-handler-mapping
  • Name: spring 4 mvc hello world class name handler mapping

Tutorials:
Create a New Maven Project in Eclipse
Configure Run on Server option on a Maven Project on Eclipse IDE

 

Step 2. Edit pom.xml file.

Set up the needed details and the project information to build the project.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.consistentcoder</groupId>
    <artifactId>spring-4-mvc-hello-world-class-name-handler-mapping</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>spring 4 mvc hello world class name handler mapping</name>
    
    <dependencies>
        <!-- Spring Framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        
        <!-- Java Servlet API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>

/pom.xml

 

Step 3. Edit web.xml file.

Integrate Spring WebMVC by mapping incoming request to the "DispatcherServlet", do this inside the "Deployment Descriptor".

<?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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>spring-4-mvc-hello-world-class-name-handler-mapping</display-name>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

/src/main/webapp/WEB-INF/web.xml

 

Step 4. Create spring-servlet.xml file.

Map the corresponding class controller of an incoming request that will create a model and will return the view file. In this example, three (3) pages should be created. The Home, About, and Contact Pages. Make the Home Class Controller the default page by setting it as the rootHandler.

<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/context 
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  
    <!-- ControllerClassNameHandlerMapping -->
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="caseSensitive" value="true" />
        <property name="rootHandler" value="homeBean" />
    </bean>
    <bean name="homeBean" class="com.consistentcoder.controllers.Home" />
    <bean class="com.consistentcoder.controllers.About" />
    <bean class="com.consistentcoder.controllers.Contact" />
  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

/src/main/webapp/WEB-INF/spring-servlet.xml

 

Step 5. Create the template file.

Set up views files by creating a new folder inside "WEB-INF", name it "jsp". After that, create a new jsp file inside it and name it "hello.jsp", then put the following code inside it.

<%@ 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>Spring 4 MVC Hello World Class Name Handler Mapping Example</title>
</head>
<body>
    <p>
        <ul>
            <li><a href="<%=request.getContextPath()%>">Home Page</a></li>
            <li><a href="<%=request.getContextPath()%>/about">About Page</a></li>
            <li><a href="<%=request.getContextPath()%>/contact">Contact Page</a></li>
        </ul>
    </p>
    <h1>${ message }</h1>
</body>
</html>

/src/main/webapp/WEB-INF/jsp/hello.jsp

 

Step 6. Create the Controller Class.

Transform and interpret each incoming request into a model. Create a new package and name it "com.consistentcoder.controllers". Create a new class inside it, name the class "Main".

Tutorials:
Create a New Package on Eclipse IDE
Create a New JAVA Class on Eclipse IDE

 

Step 6.1 Create the Home Page Controller.

Create the class file (Home.JAVA) that is mapped to the Home Page, as described on the file spring-servlet.xml.

package com.consistentcoder.controllers;

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 Home extends AbstractController {
	public ModelAndView handleRequestInternal(HttpServletRequest request,
		    HttpServletResponse response) throws Exception {
		        ModelAndView mv = new ModelAndView();
		        mv.setViewName("hello");
		        mv.addObject("message", "Spring 4 MVC Hello World<br>Class Name Handler Mapping Example");
		        return mv;
		    }
}

/src/main/java/com/consistentcoder/constrollers/Home.java

 

Step 6.2 Create the About Page Controller.

Create the Controller About.JAVA, check the file spring-servlet.xml for reference.

package com.consistentcoder.controllers;

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 About extends AbstractController {
	public ModelAndView handleRequestInternal(HttpServletRequest request,
		    HttpServletResponse response) throws Exception {
		        ModelAndView mv = new ModelAndView();
		        mv.setViewName("hello");
		        mv.addObject("message", "Hello World - About Page...");
		        return mv;
		    }
}

/src/main/java/com/consistentcoder/constrollers/About.java

 

Step 6.3 Create the Contact Page Controller.

Create the last needed Controller Contact.JAVA, again as configured on the spring-servlet.xml file.

package com.consistentcoder.controllers;

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 Contact extends AbstractController {
	public ModelAndView handleRequestInternal(HttpServletRequest request,
		    HttpServletResponse response) throws Exception {
		        ModelAndView mv = new ModelAndView();
		        mv.setViewName("hello");
		        mv.addObject("message", "Hello World - Contact Page...");
		        return mv;
		    }
}

/src/main/java/com/consistentcoder/constrollers/Contact.java

 

That's all!

Spring 4 MVC Hello World Class NameHandler Mapping Example has been developed.

 

Final Project Structure

 

What's Next? Test the application.

Start your server and browse this link. http://localhost:8080/spring-4-mvc-hello-world-class-name-handler-mapping/. Home Page will be displayed.

 

About Page

 

Contact Page

 

Note: All various handler/controller beans defined in it's application context will be found by ControllerClassNameHandlerMapping(). Thus, in this example, /about maps to the /about* request URL, and /contact maps to the /contact* request URL.

 


Reference:

  • http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-coc-ccnhm

 

Latest Tutorials



Install Eclipse Oxygen IDE on CentOS 7


Run Tomcat Server as a Service in CentOS 7


Install JAVA 1.8 and Tomcat Server 9 in CentOS 7


Launch an AWS MySQL DB Instance


Get current MySQL auto increment value of a certain TABLE.


Change MySQL auto increment value


Download and save a file from the web using JAVA


Read a file inside of JAR in JAVA


Read a file outside of JAR in JAVA


Create excel files in JAVA


Read excel files in JAVA


Install SOLR 5.x


Spring 4 MVC Multiple File Upload Example


Spring 4 MVC JSON Hello World Annotation Example


Create a File Uploader using jQuery and Bootstrap


Spring 4 MVC File Upload Example


Spring Security 4 JAVA Config In Memory Authentication Authorize Requests Security Method


Generate BCrypt Hashed Passwords using Spring Security 4


Spring Security 4 XML Config JDBC Authentication Annotation Security Method


Spring Security 4 XML Config In Memory Authentication Intercept Url Security Method


Spring Security 4 XML Config In Memory Authentication Annotation Security Method


Spring 4 MVC Hello World Annotation Example


Spring 4 MVC Hello World Bean Name Url Handler Mapping Example


Spring 4 MVC Hello World Simple Url Handler Mapping Example


Spring 4 MVC Hello World Class Name Handler Mapping Example


Generate and Configure Git SSH Key on Linux


Create a New JAVA Class on Eclipse IDE


Create a New Package on Eclipse IDE


Create a New Maven Project in Eclipse


Configure Run on Server option on a Maven Project on Eclipse IDE


Create a NodeJs Hello World example


Install NodeJs on CentOS


Integrate Maven in Eclipse


Check Apache, MySql, and PHP versions


Remove an option from a select box


Rotate an image in PHP


Select an element by name with jQuery


Check if a checkbox is checked with jQuery


Generate Random Passwords in PHP


Generate random strings using PHP


Watermark an image in PHP in four different ways


Add a text watermark using a True Type Font to an image with PHP


Add a text watermark to an image with PHP


Use imagecopymerge() to watermark an image with PHP


Watermark an image with PHP using imagecopy()


Combine a transparent PNG image on top of another image with PHP


Combine images using PHP


Write text to an image using TrueType fonts in PHP


Center a text on an image using imagestring()


Create an image with custom text in PHP


Create an image with PHP


Convert JSON to XML using PHP


Convert XML to JSON in PHP


Read XML files using jQuery


Read XML files in PHP


Create an XML file with PHP


Parse JSON file with jQuery


Parse JSON file with PHP


Create a JSON file in PHP


Know the difference between bindParam() and bindValue() in PDO


Bind a parameter to a variable using bindValue() in PDO


Bind a parameter to a variable using bindParam() in PDO


Scroll to an element using jQuery


Create a PDF file in PHP


Match the beginning of a Class or ID in jQuery


Edit an excel file using PHPExcel


Access a MySQL database from the terminal


Grant a privilege to a MySQL user on a database


Create a MySQL database user


Change font style in PHPExcel


Merge cells in PHPExcel


Change array values to lowercase or uppercase in jQuery


Check if a string is in an array in jQuery


Create an excel file in PHP


Read an excel file in PHP


Use a variable to match or replace a string in Javascript


Insert new records to a MySQL database using PDO in PHP


Update a MySQL record using PDO in PHP


Delete MySQL records using PDO in PHP


Select MySQL database records using PDO in PHP


Access MySQL database using PDO in PHP


Restore a MySQL backup file (.sql) from the terminal


Backup MySQL database into an .sql file from the terminal


Install LAMP on Ubuntu in six easy steps


Develop a Spring3 MVC Hello World Annotation Application