Intro to spring boot using JSP templates

Tired of battling environments, xml hell and dealing with the same configuration files through out applications? Spring provides an opinionated way to facilitate application development with spring-boot.

Detailed Video Notes

Hey everyone, this is Justin at Level Up Lunch. If you have ever tried to set up a Java web project you know the difficulties that go into it. Luckily with spring-boot we get convention over configuration or what the Spring guys call opinionated view on how a web project should be set up. Today we will walk through the Building an Application with Spring Boot guide. We won't go through everything but we want to cover project set up, creating a simple controller that returns a string and json response, setting up jsp within spring boot and cover how to activate the spring actuator module.

Setting up a spring boot application

[0:39]

The first thing we will want to do is set up a spring boot application. There is a few different ways to go about doing this. You can use maven, gradle or even download source code from spring guide repo. I went ahead and downloaded spring sts and it through a spring starter project. By selecting the web style it will create two classes, an Application and ApplicationTest class.

In the Application class, you will notice the generated code contains a main method that some of us are more familiar with running a console app. Spring has made it easy and created a SpringApplication class to initialize spring context. It will scan your class path and will use series of Conditional annotations such as @ConditionalOnClass and @ConditionalOnMissingBean annotations and determines what beans are available on your class path.

To see which beans definitions available, we added the following code:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    }
}

Output

Let's inspect the beans provided by Spring Boot:
JSPController
application
applicationContextIdFilter
auditEventRepository
auditListener
autoConfigurationAuditEndpoint
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
....
mappingJackson2HttpMessageConverter
messageConverters
messageSource
tomcatEmbeddedServletContainerFactory
traceEndpoint
traceRepository
viewControllerHandlerMapping
viewResolver
webRequestLoggingFilter

If you have ever run with different application servers, new developers typically have to configure many settings just to get up and running. This approach allows developers to get up and running right out of the box and focused on developing code, not configurating application servers.

Create a simple controller

[2:32]

The next series of examples we created eclipse snippets to help us along. Lets go ahead and create a HelloController that shows just how easy it is to add a controller and @RequestMappings. The controller is annotated with Spring 4 new @RestController annotation. It has two request mappings, the first is just the default and the second is to /jsontest. The /jsontest request mapping contains @ResponseBody which is delegated to the MappingJackson2HttpMessageConverter.

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Greetings from Level up lunch!";
    }

    @RequestMapping("/jsontest")
    public @ResponseBody Map<String, String> callSomething () {

        Map<String, String> map = new HashMap<String, String>();
        map.put("url", "http://www.leveluplunch.com");

        return map;
    }
}

Configuring JSPs in spring boot

[3:45]

By default spring-boot doesn't configure jsp. There are four different steps to take to configure jsp within spring boot.

Create JSP controller

First we will need to create a controller, JSPController that has a @RequestMapping /jsptest which will return a string which will resolve to a jsp file name jsp-spring-boot.jsp.

@Controller
public class JSPController {

  @RequestMapping("/jsptest")
    public String test(ModelAndView modelAndView) {

        return "jsp-spring-boot";
  }

}

Create properties file

[4:20]

The second step is create an application.properties file. If you configured spring applications before, the prefix and suffix should be natural. All the prefix and suffix is stating is, based on default root what is the prefix and suffix of the file. By default, spring will look at the /src/main/webapp folder to look for the resources.

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

If you need to change the document root directory or base root folder you can do so by using this snippet:

@ComponentScan
@EnableAutoConfiguration
public class Application implements EmbeddedServletContainerCustomizer {

    @Value("${someproperty:webapp/whereever  }")

    private String documentRoot;

    @Override
    public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
        factory.setDocumentRoot(new File(documentRoot));
    }
}

Create jsp

[5:7]

Next we will want to create the JSP file named jsp-spring-boot.jsp in /src/main/webapp/WEB-INF/jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>Hello world</h1>

</body>
</html>

Modify pom.xml

[5:37]

The last step in configuring JSP set up is to edit our pom file to include a couple extra dependencies. Remember when spring boot starts, it will scan the classpath and determine which classes are available for it to autoconfigure. The two dependencies we will want to insert are tomcat-embed-jasper and the jstl jar.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

Actuator in spring boot

[6:27]

The last example we want to cover is adding spring actuator into spring boot. Spring actuator is a submodule that produces non functional requirements/metrics that you desire within your application. One thing to note, since spring actuator is just a series of beans under the covers it also can be set up outside of boot in your traditional spring application. Lets add the following pom dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Looking at a few URLs that actuator enables, /beans will return a response of all the spring beans in spring context. /info if configured, contains commit, timestamp, information from the git.properties if it exists and any properties in the environment that has a prefix of info. /health indicates if the application is OK in case you have a health status services if your app is up and running. /dump provides detailed information about all thread in the application.

Thanks for joining in todays level up lunch.