Saturday, June 30, 2018

Java Spring Boot MVC and JSP with Maven and Visual Studio Code


In this tutorial I will explain step by step how to create from scratch a working Spring Boot MVC application, with JSP, using Maven and configure Visual Studio Code in order to develop and debug while using Hot Swap feature.

Highlight of versions used in this tutorial:

Java version: 1.8
Spring version: 2.1

Install extensions

Open Visual Studio Code
Install extensions:
  • Spring Boot Extension Pack (Pivotal)
  • Java Extension Pack (Microsoft)
This extensions will install all other extensions needed for Spring and Java.
Reload VSCode to load installed extensions.
Wait until it ends importing Java Maven Project (look at the status bar)

Generate a Spring Boot Project


  • Press F1 from VSCode
  • Select "Spring Initializr: Generate a Maven Project" and press Enter
  • Select "Java" and press Enter
  • Type the group Id, we will use the default "com.example" and press Enter
  • Type the artifact Id, we will use the default "demo" and press Enter
  • Select the spring version, we will use "2.1.0 (SNAPSHOT)" and press Enter
  • Select the required dependencies for this project: "Web, DevTools", I suggest to add also "Lombok, JPA, H2" to use the same project later for further examples and press Enter.
  • Select a folder to save the project and press Enter

VS Code will ask if you want to move to the created folder, answer YES.

Add support for JSP-EL

Edit pom.xml and add dependencies:

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

Be sure that in .vscode/settings.json has been added:

{
"java.configuration.updateBuildConfiguration": "interactive"
}

Edit main/resources/application.properties, adding the following:

spring.mvc.view.prefix: /WEB-INF/views/ spring.mvc.view.suffix: .jsp # logging.level.org.springframework: TRACE # logging.level.com: TRACE welcome.message: Hello
The first two rows are needed to set up JSP view resolver.
You can uncomment logging levels if you want to trace what is happening.
The third row is just put as example of how to use a property in the code, we will use it later.

Create the directory:
main/webapp/WEB-INF/views
and create a file index.jsp
Put this content in the file:

<!DOCTYPE HTML>
<html>
<head>
    <title>Main page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p>${greeting}</p>
</body>
</html>

Add a controller

Create the directory:
com/example/demo/controllers

And create a file HomeController.java
Fill the file with this content:

package com.example.demo.controllers;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    // inject via application.properties
    @Value("${welcome.message}")
    private String message = "Hello World";

    @RequestMapping("/")
    public String index(Model model) {
        model.addAttribute("greeting", message);
        return "index";
    }
}

Debug the application

Press F5 to launch debug configuration.

Select "Java" from the list to create a configuration to launch, a .vscode/launch.json file will be created.
This procedure will happen only the first time, when file launch.json is missing.

Press F5 again to execute the debugging.

Go to http://localhost:8080 and verify that it works.

While debugging, try changing the code, for example by adding something to model:

model.addAttribute("greeting", message + "!");

Reload the page and verify that changes are directly reflected and hot swap works correctly.
This is permitted by Spring Tools dependency and the configuration in settings.json.
In the same way you can add controllers and new methods and hot swap still will do the job.

Happy coding!



6 comments:

  1. This application has no explicit mapping for /error, so you are seeing this as a fallback.

    I get an error.
    How can I solve this?

    ReplyDelete
    Replies
    1. More likely your controller cannot be found. Be sure that:

      1) During project creation you selected "Spring Web" (not "Spring Reactive Web" or "Spring Web Services"
      2) your full controller path is:
      src/main/java/com/example/demo/controllers/HomeController.java

      Keep in mind that every spring component (and the package containing it) should be put under:
      src/main/java/com/example/demo
      in order to be recognized by Spring.

      Delete
  2. in eclipse most of the file/folder created by eclipse itself , but in vscode we have to create those file/folder, nicely explained thanks, god bless !

    ReplyDelete
  3. i too want to ask how do we configuration registers and initializes the DispatcherServlet in vscode ?

    ReplyDelete
    Replies
    1. Configuration is done automatically by making use of the application.properties file (you can just modify or add properties).
      However, if you need more freedom or additional configurations, you can just create a new class, i.e. WebConfig.java and put it in the folder com/example/demo (the starting folder for autoscan):
      This class should be annotated with @Configuration annotation and implements the WebMvcConfigurer interface, like this:

      @Configuration
      public class WebConfig implements WebMvcConfigurer {
      // ...
      // implement needed methods here
      // ...
      }

      This class will be automatically recognized by Spring (as soon as it is put in the right folder)
      You can implement also the ServletContextAware interface if you need the servlet context too.

      Delete

(c) Copyright 2020 - MyTroubleshooting.com