Starting a Spring Boot Web Application

Starting a Web Application

Here, we will modify Spring Boot - Hello World.

Changing Dependencies for a Web Application

build.gradle

dependencies {
-   compile 'org.springframework.boot:spring-boot-starter'
+   compile 'org.springframework.boot:spring-boot-starter-web'
}

When creating a web application, use the spring-boot-starter-web module.
By default, it creates a web application using Spring MVC.

Changing the Startup Method

Because the container exits after the server starts, change the code so it does not use a try-with-resources statement.

src/main/java/sample/springboot/Main.java

package sample.springboot;

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

@SpringBootApplication
public class Main {

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

Spring MVC Controller Class

When creating a class that becomes the entry point of a Web API, add @RestController to the class.
If you want a controller that corresponds to the C in MVC instead of a Web API, add the @Controller annotation.
Use @RequestMapping to map paths and HTTP methods. It feels roughly similar to JAX-RS.

src/main/java/sample/springboot/web/HelloController.java

package sample.springboot.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(method=RequestMethod.GET)
    public String hello() {
        return "Hello Spring MVC";
    }
}

Running the Application

Run with Gradle

$ gradle bootRun
(omitted)
> :bootRun

Test with curl

$ curl http://localhost:8080/hello
Hello Spring MVC

Source Code