Quick Start: Building a Web App by Spring Tool Suite
| Small purple plants in springtime |
What to build
A classic "Hello World!" message replied to a web browser from Tomcat server.
What tools are required
Spring Tool Suite (version 4 in this example)
JDK (version 8 or above)
Note: Unlike the official Quick Start guide, installation of Spring Tool Suite but not Maven or Gradle is required.
Step 1
Install Spring Tool Suite, and launch it.
Step 2
Fill out the New Spring Starter Project form to generate the starter codes.
To launch the form: File > New > Spring Starter Project
Fill out the two pages of the form as below.
First page:
Notice that Gradle type is chosen for this example.
Change project Name, Group, Artifact, and Package to yours.
Second page:
In the "Available" text field, enter "Web" to search for the web-related components.
Select "Spring Web".
Click "Finish" to generate the codes.
Step 3:
On the navigation panel, locate the Java file "WebdemoApplication.java" and double-click to open it.
Modify the code by adding a hello method etc.:
Here is the code for copy-and-paste:
package com.calmalgo.spring.webdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class WebdemoApplication { public static void main(String[] args) { SpringApplication.run(WebdemoApplication.class, args); } @GetMapping("/hello") public String hello(@RequestParam(value = "name", defaultValue = "World") String name) { return String.format("Hello %s!", name); } }
Step 4
Run the application: Run > Run
That includes launching the Tomcat server.
Step 5:
At the same workstation, launch a web browser.
Go to address: localhost:8080/hello
The web browser will receive a reply of "Hello World!"
Additional step for experiment:
Modify the hello method to manipulate how to generate a reply to the browser.
Example 1:
@GetMapping("/hello") public String hello(@RequestParam(value = "name", defaultValue = "World") String name) { UnaryOperator<String> replyOp = n -> { return String.format("Hello %s", n); }; return replyOp.apply(name);
}
Example 2:
@GetMapping("/morning") public String morning(@RequestParam(value = "name", defaultValue = "World") String name) { UnaryOperator<String> replyOp = n -> { return String.format("Good morning %s", n); }; return replyOp.apply(name); }
Comments
Post a Comment