March 6, 2023

Create a Spring Boot project

Create a Spring Boot project

  1. Use Spring Initializr to config and create a “Web project”.

  2. Choose Project Management Tools, Language, Spring Boot version (DO NOT choose SNAPSHOT), and fill in Project Metadata (Group/Artifact, Name, Description, Package name, Packaging and Java version).

  3. Click ADD DEPENDENCIES and choose the dependencies you need.

    Below is an example of mine.

    Screenshot 2023-03-06 at 6.34.20 pm

  4. Click GENERATE, it will download a ZIP file of a web application with the configuration you choose.

  5. Unzip the file and open the folder in your IDE. Here I use IntelliJ IDEA.

  6. Modify the code in src/main/java/YourGroupName/YourProjectName

    DemoProject.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.example.demo;
    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 DemoApplication {
    public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
    }
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
    return String.format("Hello %s!", name);
    }
    }

    The @RestController annotation tells Spring that this code describes an endpoint that should be made available over the web. The @GetMapping(“/hello”) tells Spring to use our hello() 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 "World" by default.

  7. Run the project

    image-20230306190944647

  8. Open the browser, and enter http://localhost:8080/hello, you should see Hello World now.

    If you add ?name=YourName to the end of the URL, you will see Hello World being replaced by Hello YourName on the page now.

    image-20230306191302917



Reference

About this Post

This post is written by Andy, licensed under CC BY-NC 4.0.

#Spring Framework