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 
    @Controller
    public class HomeController {
    
        // Processing request http://domain.com/context/hello
        @RequestMapping("/hello")
        public ModelAndView helloHandler() {
    
            ModelAndView mav = new ModelAndView();
    
            // Use the view named "home" to display the data
            mav.setViewName("home");
            // 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

Edit

webmvc-config.xml  

Below

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

Add

    <!-- 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" />
    </bean>

  • 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" %>
<html>
  <head><title>Spring MVC Simple Application</title></head>
<body>

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

</body>
</html>

Testing

Browse to

http://host.domain.com/my_app_context/hello