Spring MVC: Annotation based “Hello World” web application

In previous article, we have discussed about creating simple “Hello World” web application using XML based configuration. But, now we will extend the same web application by removing the tedious XML configuration with much improved Annotation based configuration.

Goal: XML configuration-less with highly supported Annotation based configuration

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Spring-4.0.0-RELEASE
  • Apache Maven 3.0.4
  • Apache Tomcat 7.0.54

Mavenize or download required jars

Add Spring-4.0.0 dependencies to the pom.xml

	<dependencies>
		<!-- Spring dependencies -->
		<!-- for compile only, your container should have this -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL tag library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Spring Core and Context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure

  • src/test/java–> test related files, mostly JUnit test cases
  • src/main/java –> create source java files under this source folder
  • src/main/resources –> all configuration files placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application
  • create a package “com.spring.series.mvc.controller” under src/main/java folder for our app

1_SpringMVC-Annotation

Web application:

For any web application, entry point is web.xml which describes how the incoming http requests are served or processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading the files particular to project requirements & contains respective listener.

With this introduction, we will understand how did we configured web.xml for this sample Spring MVC web application which supports Annotation

web.xml (the entry point à under WEB-INF)

Note: Normally, URI for any http request is looks like

http://://

This web.xml file describes,

  • all http requests with wild card pattern “/” will be intercepted by the configured servlet called “DispatcherServlet” (org.springframework.web.servlet.DispatcherServlet)
  • </servlet-name> name mentioned in the web.xml is mvc-dispatcher, which on loading/exploading the war into the application server(Tomcat application server for our example) looks for the servlet filename called “mvc-dispatcher-servlet.xml”
  • <context-param> with its attributes describes the location of the file from where it has to be loaded
  • “mvc-dispatcher-servlet.xml” is the file which describes how exactly specific http requests are handled or which controllers gets invoked for certain http requests. We will see “mvc-dispatcher-servlet.xml” file for our Spring MVC web application

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

	<!-- project display for web application -->
	<display-name>SpringMVC-Annotation</display-name>

	<!-- welcome file list -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<!-- Spring MVC DispatcherServlet: dispatches HTTP requests to registered controllers -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern><!-- *.html -->
	</servlet-mapping>

	<!-- location of the root application context xml file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
	</context-param>

	<!-- context loader listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>

Dispatcher Servlet

Below mvc-dispatcher-servlet.xml file defines,

  • <context:component-scan base-package=”” /> this tag scans all classes & sub-classes under the base-package attribute and register them with container
  • Basically these classes are annotated with @Controller on top of the class
  • other bean element, basically defines the logic for view resolver i.e.; viewName returned by the Controller which will be sandwiched between the prefix (WEB-INF/jsp) & suffix (.jsp)
  • Now, there should be a file under the directory as defined i.e.; (WEB-INF/jsp/<viewName>.jsp
  • Otherwise, not found exception thrown

mvc-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- scan packages to register controllers which are annotated -->
	<context:component-scan base-package="com.spring.series.mvc.controller" />

	<!-- view resolver for rendering the final output -->
	<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>

Let’s see coding in action

 

My Controller

This is the actual request handler which is invoked from “DispatcherServlet” to service the incoming http request (with sample URL pattern http://localhost:8081/SpringMVC-XMLBased/controller/firstmvc.htm)

  • Simple Java class annotated with @Controller which will be scanned & registered with the container
  • Also, you can see another annotation @RequestMapping (“/controller) –> which defines the basic URL path for this particular class
  • Add a method of your choice and annotate with @RequestMapping (“/firstmvc) –> which defines further path for this particular method
  • There is one attribute called method in the @RequestMapping annotation –> which defines the whether the http request is GET or POST
  • This method is returning ModelAndObject instance which carries the viewName along with data model to display to end user
  • modelAndView.addObject(“message”, “Welcome To Spring MVC Annotation based web application”); this is the line which sets the message to be routed to “DispatcherServlet” to display data to end user after resolving the viewName it got in the form of ModelAndView object

MyFirstMVController.java

package com.spring.series.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/controller")
public class MyFirstMVController {

	// http://localhost:8080/SpringMVC-Annotation/controller/firstmvc.htm

	@RequestMapping(value="/firstmvc", method=RequestMethod.GET)
	public ModelAndView firstMVController() {

		ModelAndView modelAndView = new ModelAndView("showMessage");
		modelAndView.addObject("message", "Welcome To Spring MVC Annotation based web application");
		return modelAndView;
	}
}

That’s all with the core part of the Spring MVC Framework; we will look into building a view to output the result to the end user after rendering it.

View Resolver: The JSP (Java Server Page)

  • simple JSP file to display the “message” to the end user, once entering http request
  • ${message} this is where the message will be outputted after rendering the result by the “DispatcherServlet”

showMessage.jsp (under WEB-INF/jsp)

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
	<head>
		<meta charset="utf-8">
		<title>Spring MVC Annotation</title>
	</head>
	<body>

<h2>${message}</h2>

	</body>
</html>

All efforts to see the below screen shot

You will see the below rendered result J
2_SpringMVC-Annotation-direct-result

The other WAY

Earlier, we have entered the URL directly into the browser to view the rendered output but at times while building big enterprise application you may need to flow through pages by clicking links. So here it is covered to show one such scenario

Steps to follow:

  • You have got index.jsp (under webapp folder) –> entering the URL http://<server>:<port>/<root_context> on the browser will displays the welcome page listed in the web.xml
  • index.jsp is designed to have a simple <a href=“controller/firstmvc.htm”> link for page redirection
  • On clicking this link we have given the control to the controller after consulting DispatcherServlet which redirects to the showMessage.jsp

index.jsp (under webapp)

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
	<head>
		<meta charset="utf-8">
		<title>Welcome to Spring MVC</title>
	</head>
	<body>
		<a href="controller/firstmvc.htm">MY First Annotated MVC Controller</a>
	</body>
</html>

Enter URL in the browser <http://localhost:8081/SpringMVC-Annotation/>

3_SpringMVC-Annotation-index-link

You will see anchor links with text  “MY First Annotated MVC Controller”, which actually invokes the MyFirstMVController which annotated with @Controller annotation after consulting mvc-dispatcher-servlet.xml and returns the ModelAndObject object

Click the link <MY First Annotated MVC Controller>

The gotcha done!!
Now, see the rendered result

4_SpringMVC-Annotation-index-result

Conclusion: With this demo, we have seen how much it is easier to code Spring MVC web application with few easy remembering Annotations in the source code itself & saves lot of time by removing the mapping of tedious XML configuration in the Dispatcher-Servlet file.

Download project

Spring-MVC-Annotation-Based (4kB)

 

Read Also:

Happy Coding !!
Happy Learning !!

Spring MVC: Multi-Controller actions using @Controller
Spring MVC: Creating “Hello World” web application based on XML configuration