How to create a website with Spring Boot and serve static content

3232


Spring Boot makes it easy to create Spring based Applications easy and Quick. In this tutorial i'll show you how to create a website and service static content using Springboot.

<iframe width="560" height="315" src="https://www.youtube.com/embed/5L1PQKhKtiA" frameborder="0" allowfullscreen></iframe>

Prerequisites:

  1. Java
  2. Eclipse with Gradle (All latest versions of Eclipse get the Gradle by default)

First open your eclipse and create a new Gradle project. Once this is done you will see a project structure something like below.

Sample gradle project structure

Open the build.gradle file and add the SpringBoot dependencies. You can check the latest spring boot version by visiting the spring boot's official website. At the time of making this tutorial its 1.5.6 & 2.0.0 is beta.
Spring Boot's Gradle dependency:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.6.RELEASE")
}

Now your build.gradle looks something like below

apply plugin: 'java-library'
repositories {
    jcenter()
}

dependencies {
    api 'org.apache.commons:commons-math3:3.6.1'
    implementation 'com.google.guava:guava:21.0'
    testImplementation 'junit:junit:4.12'
    
    //Spring Boot
    compile("org.springframework.boot:spring-boot-starter-web:1.5.6.RELEASE")
}

Once you are done with adding the dependency Right click on the project and goto Gradle and then click Refresh Gradle project, this will download you the dependencies you have just added in build.gradle file.

Now create a package in your source folder and create your main program in this tutorial i am naming my main program as Start.java
Paste the following code in Start.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Start {
	public static void main(String[] args) {
		SpringApplication.run(Start.class, args);
	}
}

Now create another source folder /src/main/resources to keep your resources. In the /src/main/resources create folder and name it as 'public' or 'static' as spring look for these folder names to find the static content. In the public or static folder add your static content.
Now your project structure should look like below

info-about-image

Now you are ready to start your spring boot application do that by running Start.java as a main program. If you start the main program The Spring boot will start with the default port which is 8080 and shows the following logs

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

2017-08-19 01:13:14.302  INFO 99060 --- [           main] com.example.Start                        : Starting Start on MacBook-Pro.local with PID 99060 (/Users/experimental/Documents/githome/SpringBootStaticWebsiteExample/bin started by experimental in /Users/experimental/Documents/githome/SpringBootStaticWebsiteExample)
2017-08-19 01:13:14.315  INFO 99060 --- [           main] com.example.Start                        : No active profile set, falling back to default profiles: default
2017-08-19 01:13:14.354  INFO 99060 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbedde<a class="__cf_email__" href="/cdn-cgi/l/email-protection" data-cfemail="3f5b685a5d7e4f4f53565c5e4b5650517c50514b5a474b7f0a0e5d0d08065c06">[email protected]</a><script data-cfhash='f9e31' type="text/javascript">/* <![CDATA[ */!function(t,e,r,n,c,a,p){try{t=document.currentScript||function(){for(t=document.getElementsByTagName('script'),e=t.length;e--;)if(t[e].getAttribute('data-cfhash'))return t[e]}();if(t&&(c=t.previousSibling)){p=t.parentNode;if(a=c.getAttribute('data-cfemail')){for(e='',r='0x'+a.substr(0,2)|0,n=2;a.length-n;n+=2)e+='%'+('0'+('0x'+a.substr(n,2)^r).toString(16)).slice(-2);p.replaceChild(document.createTextNode(decodeURIComponent(e)),c)}p.removeChild(t)}}catch(u){}}()/* ]]> */</script>: startup date [Sat Aug 19 01:13:14 IST 2017]; root of context hierarchy
2017-08-19 01:13:15.067  INFO 99060 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-19 01:13:15.076  INFO 99060 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-08-19 01:13:15.077  INFO 99060 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-19 01:13:15.148  INFO 99060 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-08-19 01:13:15.148  INFO 99060 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 796 ms
2017-08-19 01:13:15.238  INFO 99060 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-19 01:13:15.241  INFO 99060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-19 01:13:15.241  INFO 99060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-19 01:13:15.242  INFO 99060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-19 01:13:15.242  INFO 99060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-19 01:13:15.457  INFO 99060 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbedde<a class="__cf_email__" href="/cdn-cgi/l/email-protection" data-cfemail="9ffbc8fafddeefeff3f6fcfeebf6f0f1dcf0f1ebfae7ebdfaaaefdada8a6fca6">[email protected]</a><script data-cfhash='f9e31' type="text/javascript">/* <![CDATA[ */!function(t,e,r,n,c,a,p){try{t=document.currentScript||function(){for(t=document.getElementsByTagName('script'),e=t.length;e--;)if(t[e].getAttribute('data-cfhash'))return t[e]}();if(t&&(c=t.previousSibling)){p=t.parentNode;if(a=c.getAttribute('data-cfemail')){for(e='',r='0x'+a.substr(0,2)|0,n=2;a.length-n;n+=2)e+='%'+('0'+('0x'+a.substr(n,2)^r).toString(16)).slice(-2);p.replaceChild(document.createTextNode(decodeURIComponent(e)),c)}p.removeChild(t)}}catch(u){}}()/* ]]> */</script>: startup date [Sat Aug 19 01:13:14 IST 2017]; root of context hierarchy
2017-08-19 01:13:15.501  INFO 99060 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-08-19 01:13:15.501  INFO 99060 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-19 01:13:15.522  INFO 99060 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-19 01:13:15.522  INFO 99060 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-19 01:13:15.554  INFO 99060 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-19 01:13:15.571  INFO 99060 --- [           main] oConfiguration$WelcomePageHandlerMapping : Adding welcome page: class path resource [public/index.html]
2017-08-19 01:13:15.656  INFO 99060 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-08-19 01:13:15.699  INFO 99060 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-19 01:13:15.702  INFO 99060 --- [           main] com.example.Start                        : Started Start in 11.631 seconds (JVM running for 11.912)

Now go to your browser and hit http://localhost:8080 and you should see your website up and be running there

Springboot Hello world