创建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

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值