Here, I want to print a sentence and when I entered my name then it should my name.
1. An Integrated Developer Environment (IDE). Popular choices include IntelliJ IDEA, Spring Tools, Visual Studio Code, or Eclipse, and many more if have a choice.
2. A Java™ Development Kit (JDK), I recommend AdoptOpenJDK version 8 or version 11.
Use www.start.spring.io to build a “web” project. In the “Dependencies” search box during and append the “web” dependency as shown in the screenshot given below. click on the “Generate” button, then you need to download the zip. After download unpack it into a folder on your computer.
The current version of Spring boot exchanges regularly. Simply choose the latest release (but not snapshot).
Click on 'Add dependencies', type 'Web' in the search box, then click on the dependency 'Spring Web' to choose it.
Projects created by start.spring.io include Spring Boot, a framework that gives Spring ready to work inside your app, but without much code or configuration required. Spring Boot is the instantly and most popular way to start Spring projects.
Open up the project in your IDE and locate the Application.java
file in the src/main/java/com/example
folder. Now replace the contents of the file by adding the extra method and annotations shown in the code below. You can copy and paste the code and also just type it.
package com.example;
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
@GetMapping("/hello")
public String example(@RequestParam(value = "name", defaultValue = "welcome to spring world!") String name)
{
return String.format("Hello %s!", name);
}
}
The example()
method we’ve added is designed to get a String parameter called name
, and then join this parameter with the word "Hello"
in the code. This means that if you set your name to “Shivani”
in the request, the response would be “Hello Shivani”
.
The @RestController
annotation indicates Spring that the code represents an endpoint that should be done available over the web. The @GetMapping(“/hello”)
tells Spring to use our example()
method to answer requests that get sent to the http://localhost:8080/hello
address. Finally, the @RequestParam
is telling Spring to expect a name
value in the request, but if it’s not there, it will use the word “welcome to spring the world!
” by default.
Let’s build the project and execute the program. Open a command line (or terminal) or you can do right click in same file and select run -> Java Application only) and navigate to the folder where you have the project files. We can build and run the application by resulting the following command:
MacOS/Linux:
./mvnw spring-boot:run
Windows:
mvnw spring-boot:run
You will see some output that looks like very similar to this while hit this URL http://localhost:8080/hello
:
Hello welcome to the spring world
Thanks!