Spring Boot w/ JSP

Java, maven, programming, Spring Boot

Project Setup

From the CLI or http://start.spring.io/, initialize a project with “web” capability.  What ends up happening is addition of the dependency:

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

Start with this directory structure. Be sure the controller (and any other Spring beans) are located under where the Application class (JspDemoApplication in this example) is.

...
  src/
    main/
      java/
        org/
          van/
            jspdemo/
              JspDemoApplication.java
              controller/
                DemoController.java
      resources/
        application.properties
      webapp/
        WEB-INF/
          jsp/
            demoindex.jsp

Controller and View

Add a controller file DemoController.java (see tree above for location):

...

@Controller
@RequestMapping("/jspdemo")
class DemoController { 
  @RequestMapping("/index")
  public String index(@RequestParam("name") String name, Model model) {
    model.addAttribute(name.toUpperCase());
    return "demoindex";  // view/JSP name
  }
}

Then the view file demoindex.jsp (see tree above for location). NOTE that the webapp/WEB-INF/jsp subdirectory needs to be created.

<html>
  <div>
    Hello, ${name}.
  </div>
</html>

Add support for JSP

Add these dependencies:

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

Add these to application.properties:

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

Leave a Reply