SPRING BOOT HELLO WORLD EXAMPLE

A Simple  Spring boot webapplication example, using Embedded Tomcat + JSP, and package as an executable JAR file.

Technologies used :

  1. Spring Boot 1.5.6 RELEASE
  2. Spring 4.3.10
  3. Embeded Tomcat 8.5.16
  4. Maven 3.5.0
  5. Java8

Here is the directory structure of the sample web application,

1) Project Directory Structure.

 

2) Maven And Jave Version:

 

3) Pom.xml file:

In this file, we will declare dependency of jstltomcat-embed-jasper,ecjwhich we would need to compile JSP files.

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
  <artifactId>SpringBootSampleWebApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
  <name>SpringBootSampleWebApp</name>
<description>Demo project for Spring Boot With JSP View</description>
  <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
  <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
  <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
    <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Need this to compile JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- Need this to compile JSP -->
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
  </dependencies>
  <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

4) Spring Boot

4. 1)

We just need to annotate our pojo class with @SpringBootSampleWebAppApplication and our class will be ready to load all the spring boot configuration and also load required controllers and beans into the embedded tomcat's container.

package com.milan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootSampleWebAppApplication {
  public static void main(String[] args) {
SpringApplication.run(SpringBootSampleWebAppApplication.class, args);
}
}

4.2)

We will create one controller, to handle http request. To create controller and tell spring that our pojo class is controller, all we need to do is to annotate that class with @Controller annotation, and map that controller with specific url by annotation our pojo class with @RequestMapping annotation and giving it url in form of string which wills server from the host address root.

package com.milan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {
    @GetMapping
String getView(Model model) {
model.addAttribute("msg", "Hello there, This message has been injected from the controller method");
return "helloworld";
}
}

4.3)

We would need to configure ViewResolver but thanks to spring boot, we can do that directly from the application.properties file, so we will add below code in application.properties file.

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

5) JSP

We will create file helloworld.jsp in the /src/main/webapp/WEB-INF/jsp/folder and in that file, we will write below code, which will render html along with the message passed in the model object from controller's method.

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<body>
<h2>${msg}</h2>
</body>
</html>

6) Building Jar with Maven

Once, we are done with above code, we will build our project, using maven commands and then execute as standalone jar using standard java’s jar execution command.

6.1)

  1. Navigate to your project directory
  2. clean and then package your project using maven and then repackage your project using spring-boot plugin of maven.
  3. Once you execute step 2’s commands, it’ll create jar in the target directoy of your project directory.
  4. Finally, execute jar using standard java’s jar execution command as shown in below snippet
cd <TO_YOUR_PROJECT_DIR>
mvn clean package spring-boot:repackage
java -jar target/<YOUR_PROJECT_CREATED_JAR>

7) Execution

.   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2017-08-30 17:13:25.371  INFO 1901 --- [           main] c.m.SpringBootSampleWebAppApplication    : Starting SpringBootSampleWebAppApplication on localhost with PID 1901 (/home/milankumar1/IdeaProjects/SpringBootSampleWebApp-jsp/target/classes started by milankumar1 in /home/milankumar1/IdeaProjects/SpringBootSampleWebApp-jsp)
2017-08-30 17:13:25.374 INFO 1901 --- [ main] c.m.SpringBootSampleWebAppApplication : No active profile set, falling back to default profiles: default
2017-08-30 17:13:25.458 INFO 1901 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@15d9bc04: startup date [Wed Aug 30 17:13:25 IST 2017]; root of context hierarchy
2017-08-30 17:13:26.683 INFO 1901 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-30 17:13:26.693 INFO 1901 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-08-30 17:13:26.694 INFO 1901 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-30 17:13:26.876 INFO 1901 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2017-08-30 17:13:26.879 INFO 1901 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-08-30 17:13:26.879 INFO 1901 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1426 ms
2017-08-30 17:13:26.965 INFO 1901 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-30 17:13:26.968 INFO 1901 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-30 17:13:26.968 INFO 1901 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-30 17:13:26.968 INFO 1901 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-30 17:13:26.968 INFO 1901 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-30 17:13:27.160 INFO 1901 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@15d9bc04: startup date [Wed Aug 30 17:13:25 IST 2017]; root of context hierarchy
2017-08-30 17:13:27.199 INFO 1901 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/helloWorld],methods=[GET]}" onto java.lang.String com.milan.HelloWorldController.getView(org.springframework.ui.Model)
2017-08-30 17:13:27.202 INFO 1901 --- [ 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-30 17:13:27.202 INFO 1901 --- [ 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-30 17:13:27.225 INFO 1901 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-30 17:13:27.225 INFO 1901 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-30 17:13:27.255 INFO 1901 --- [ 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-30 17:13:27.343 INFO 1901 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-08-30 17:13:27.374 INFO 1901 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-30 17:13:27.376 INFO 1901 --- [ main] c.m.SpringBootSampleWebAppApplication : Started SpringBootSampleWebAppApplication in 2.392 seconds (JVM running for 3.312)

Useful Resources:

spring boot web application example

 

Also search:

spring boot jpa 

spring boot devtools