Spring Boot MVC Example

By Yashwant Chavan, Views 89092, Last updated on 14-Apr-2019

In this tutorial we are going to learn How to create simple web application with Spring Boot. Spring boot will help to speed your application development because easy to setup application with minimal configuration.Spring Boot gets package up an application in a jar file, with a full Tomcat server embedded.

tags spring spring-mvc spring-boot

Spring Boot Eclipse Project Setup

spring boot gradle eclipse project

Getting the required dependencies with Gradle

First of all we have to get the required dependencies with Gradle. We can do this by declaring the following dependencies in our build.gradle file.

The Spring Boot gradle plugin helps to collects all the jars on the classpath and builds into a single runnable jar, which makes it more convenient to execute and transport your service. It find outs the public static void main() method class (Application.java) to flag as a runnable class.

buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-milestone" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'spring-boot'

jar {
    baseName = 'spring-boot-example'
    version =  '1.0'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-milestone" }
}

configurations {
    providedRuntime
}

dependencies {
    compile ("org.springframework.boot:spring-boot-starter-web")
    providedRuntime("org.apache.tomcat.embed:tomcat-embed-jasper")
    
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.0'
}

Compile and Build

I am using Gradle Eclipse plugin to build and deploy the project. Gradle Eclipse support is developed by the SpringSource STS team. You can either use it via STS or install it separately.

Spring Boot build project using gradle

You can also use gradle clean build command to build your project thru command line.

Build Output

[sts] -----------------------------------------------------
[sts] Starting Gradle build for the following tasks: 
[sts]      :clean
[sts]      :build
[sts] -----------------------------------------------------
:clean
:compileJava
:processResources
:classes
:war
:bootRepackage
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build

BUILD SUCCESSFUL

Total time: 1.37 secs
[sts] -----------------------------------------------------
[sts] Build finished succesfully!
[sts] Time taken: 0 min, 1 sec
[sts] -----------------------------------------------------

Define Application Context Root in Properties File

To declare project specific configuration we need to create a file called application.properties file is located under path /src/main/resources/application.properties and make sure that it is available under classpath. Here you can configure the server.contextPath and server.port

server.contextPath=/SpringBootExamples
server.port=8080

HelloWorldController

Create a controller class called as HelloWorldController and annotate it with @Controller. Define the simple get method as hello() along with @RequestMapping annotation. It simply forwards your matching request to hello.jsp page along with name variable value.

package com.technicalkeeda.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
public class HelloWorldController {

 @RequestMapping(value = "/hello", method = RequestMethod.GET)
 public ModelAndView hello() {
  return new ModelAndView("hello").addObject("name", "Yashwant");
 }

}

Spring Boot Web Mvc Java Base Configuration

Prior to Spring Boot we define all our application specific configuration in spring bean definition Xml file. But this time we do not required to do much configurations because we are using spring boot.

As @Configuration is meta-annotated with @EnableWebMvc, @Configuration indicates that the class can be used by the Spring for web application configuration. This flags that the application as a web application and activates key behaviors such as setting up a DispatcherServlet

Here we have provided InternalResourceViewResolver in this class to support jsp files.

package com.technicalkeeda.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class ApplicationConfigurerAdapter extends WebMvcConfigurerAdapter{

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

hello.jsp

This is the simple jsp page (/WEB-INF/jsp/hello.jsp) which display the 'name' variable value.

<html>
 <head><title>Hello world Example</title></head>
 <body>
     <h1>Hello ${name}, How are you?</h1>
 </body>
</html> 

Application.java

This is the simple java class with main() method along with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.

The @ComponentScan annotation tells Spring to search recursively through the com.technicalkeeda package and its children for classes marked directly or indirectly with Springs @Component annotation.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. As we have annotated @EnableAutoConfiguration there is no need to to define the Spring MVC DispatcherServlet configuration and web.xml

package com.technicalkeeda;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

}

Run


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.3.RELEASE)

2014-09-24 08:44:15.183  INFO 5772 --- [           main] com.technicalkeeda.Application           : Starting Application on swami-samartha with PID 5772 (C:\javaworkspace\SpringBootExamples\bin started by swami in C:\javaworkspace\SpringBootExamples)
2014-09-24 08:44:15.211  INFO 5772 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1835282: startup date [Wed Sep 24 08:44:15 IST 2014]; root of context hierarchy
2014-09-24 08:44:16.134  INFO 5772 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-09-24 08:44:16.256  INFO 5772 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-09-24 08:44:16.257  INFO 5772 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.54
2014-09-24 08:44:16.786  INFO 5772 --- [ost-startStop-1] o.a.c.c.C.[.[.[/SpringBootExamples]      : Initializing Spring embedded WebApplicationContext
2014-09-24 08:44:16.786  INFO 5772 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1576 ms
2014-09-24 08:44:16.907  INFO 5772 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-09-24 08:44:17.118  INFO 5772 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.technicalkeeda.controller.HelloWorldController.hello()
2014-09-24 08:44:17.124  INFO 5772 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-09-24 08:44:17.124  INFO 5772 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-09-24 08:44:17.141  INFO 5772 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
2014-09-24 08:44:17.485  INFO 5772 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-09-24 08:44:17.560  INFO 5772 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-09-24 08:44:17.561  INFO 5772 --- [           main] com.technicalkeeda.Application           : Started Application in 2.644 seconds (JVM running for 2.829)

Enter the URL (http://localhost:8080/SpringBootExamples/hello) in your web browser and see the result is being displayed

spring boot mvc example output
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]