Spring MVC - Sample Application

Spring Application Business Logic

Spring Controller is a special Spring MVC class that holds the business logic to process a request

  • Create src/main/java/com/mydomain/springweb/controller/home/HomeController.java
    package com.mydomain.springweb.controller.home;
    // Annotate as a controller 
    public class HomeController {
        // Processing request http://domain.com/context/hello
        public ModelAndView helloHandler() {
            ModelAndView mav = new ModelAndView();
            // Use the view named "home" to display the data
            // Add a model object to be displayed by the view
            mav.addObject("message", "welcome to spring mvc");
            return mav;
  • RequestMapping : The Http URL Request that this class is handling
  • mav.setViewName: The name of the view in rendering the output

Configure Controller & View for Spring MVC




    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>


    <!-- Scans for application @Components to deploy -->
    <context:component-scan base-package="com.mydomain.springweb.controller.home" />

    <!-- Mapping a view name to a JSP page -->
    <!-- E.g. the view "home" will map to /WEB-INF/jsp/home.jsp -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
	<property name="viewClass"
		value="org.springframework.web.servlet.view.JstlView" />
	<property name="prefix" value="/WEB-INF/jsp/" />
	<property name="suffix" value=".jsp" />

  • component-scan scans the specific package and deploy all Spring MVC Controllers automatically
  • View resolver map a view name in a Spring MVC controller to a JSP file explicitly

Create the JSP View

Create src/main/webapp/WEB-INF/jsp/home.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <head><title>Spring MVC Simple Application</title></head>

  <c:out value="${message}"/>



Browse to