创建SpringBoot Helloword 程序详细步骤

本文档实现SpringBoot hello word 程序,翻译于Spring | Quickstart

一、项目创建步骤

1.1 创建项目

在官网Spring Initializr上创建项目

请添加图片描述

1.2 添加代码

在IDE中打开项目并在src/main/java/com/zouhu/helloword文件夹中找到HellowordApplication.java文件,现在通过添加下面代码中显示的额外方法和注释来更改文件的内容。

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);
    }
}

hello()方法被设计为采用一个名为name的String参数,然后将该参数与代码中的单词“Hello”结合起来。这意味着如果您在请求中将姓名设置为“Amy”,则响应将是“Hello Amy”。

@RestController注释告诉Spring,这段代码描述了一个应该在Web上可用的端点。

@GetMap(“/hello”)告诉Spring使用我们的hello()方法来回答发送到http://localhost:8080/hello地址的请求。

最后,@RequestParam告诉Spring期望请求中有一个名称值,但如果不存在,它将默认使用单词“World”

1.3 运行

编译并运行程序。

根据启动界面可以看到以下信息:Spring Boot的嵌入式Apache Tomcat服务器充当网络服务器,并在localhost端口8080上侦听请求。

请添加图片描述

打开浏览器,在顶部的地址栏中输入http://localhost:8080/hello即可访问

也可以通过添加参数来访问http://localhost:8080/hello?name=zouhu

请添加图片描述

参考教程

Spring | Quickstart

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-05 17:30:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-05 17:30:06       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-05 17:30:06       82 阅读
  4. Python语言-面向对象

    2023-12-05 17:30:06       91 阅读

热门阅读

  1. 软件工程 单选多选补充 复刻

    2023-12-05 17:30:06       65 阅读
  2. leetcode 208. 实现 Trie (前缀树)

    2023-12-05 17:30:06       55 阅读
  3. Android 14 CarAudioService

    2023-12-05 17:30:06       53 阅读
  4. Dockerfile 与 Docker Compose区别

    2023-12-05 17:30:06       41 阅读
  5. 分布式和集群区别和优势

    2023-12-05 17:30:06       56 阅读
  6. 关于嵌入式系统一些名词的小结(ARM/CORTEX/STM32等)

    2023-12-05 17:30:06       49 阅读