SpringExamples

Spring MVC hello world example

By Admin | Filed Under: Spring WebMVC

In this spring mvc example, we will create a bare minimum running application with only single view. The purpose of this article is show you that how much it is easy to setup and run a web application using spring framework. On later posts, we will add features (read complexity) in this hello world application.

Table of contents

Project Structure
Spring MVC Dependencies
Web Configuration
Dispatcher Servlet Configuratio
Controllers
JSP Views
Demo

Project Structure

Spring MVC Project Structure
Spring MVC Project Structure

Spring MVC Dependencies

At minimum, you need spring-webmvc dependency along with taglibs to render the pages. If you are using embedded server than you will include support of JSP and servlets as well.

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.springexamples</groupId>
	<artifactId>mvc</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>mvc Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<failOnMissingWebXml>false</failOnMissingWebXml>
		<spring.version>5.0.0.RELEASE</spring.version>
		<servlets.version>3.1.0</servlets.version>
		<jsp.version>2.3.1</jsp.version>
		<jstl.version>1.2.1</jstl.version>
		<tld.version>1.1.2</tld.version>
	</properties>
	<dependencies>
		<!-- Spring MVC Dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<!-- Servlet Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlets.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSP Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>
		
		<!-- JSTL Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${tld.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>mvc</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<!-- Embedded Apache Tomcat required for testing war -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Web Configuration

A bare minimum web MVC configuration includes some annotations and view resolver bean.

package com.springexamples.mvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

//Spring web mvc configurations
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.springexamples.mvc" })
public class WebMvcConfig implements WebMvcConfigurer {

	//View resolver bean
	@Bean
	public InternalResourceViewResolver resolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setViewClass(JstlView.class);
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
}

Dispatcher Servlet Configuration

Then we need to configure most important Spring class i.e. dispatcher servlet.

package com.springexamples.mvc.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends 
		AbstractAnnotationConfigDispatcherServletInitializer {

	// Root level configurations
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] {  };
	}

	// Servlet level configuration
	// Useful if you have multiple dispatcher servlets
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { WebMvcConfig.class };
	}

	// DispatcherServlet mapping
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
}

Controllers

A controller class is responsible for handling incoming requests, after dispatcher servlet maps the request to one of ints specific method (usually by URL matching).

package com.springexamples.mvc.home;

import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
 * Home page controller. It has methods which are invoked by user 
 * interactions on home page.
 * */
@Controller
public class HomepageController {
	
	@GetMapping("/")
	public String welcome(Locale locale, Model model) {
		return "home";
	}
}

JSP Views

Now write the view code in suitable technology. In this project, its JSPs.

<!-- Home page of the application -->
<html>
<head>
<title>SpringExamples.com MVC App</title>
</head>
<body>
	<h1>Minimum Spring MVC Example</h1>
	<h2>SpringExamples.com says - Hello World !!</h2>
</body>
</html>
<!-- This page is only for forwarding all root URL requests to home page -->
<%@page language="java" %> 
<%
    String redirectURL = "/home";
    response.sendRedirect(redirectURL);
%>

Demo

To run the above application, run it as maven build command and use the goal as ‘tomcat7:run’ as below.

tomcat7-run maven goal
tomcat7-run maven goal

The embedded server will start at port 8080. Test the application at – http://localhost:8080 URL.

Application at localhost
Application at localhost
Download Sourcecode

Happy Learning !!

Ask Questions & Share Feedback Cancel reply

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

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Spring Boot Tutorial

  • Hello world example
  • Which main class
  • Print all beans
  • Embedded jetty server
  • CommandLineRunner
  • Custom banner
  • Change Root Path and Server Port

Spring Tutorial

  • IoC Container
  • Java Configuration

Spring WebMVC Tutorial

  • Minimum required config

Copyright © 2016 · springexamples.com · All Rights Reserved. | Sitemap