使用SpringBoot搭建第一个HelloWorld程序
基于GitHub项目xkcoding/**spring-boot-demo**进行学习
项目地址:https://github.com/xkcoding/spring-boot-demo
配置文件application.yaml
- 设定端口号为8080,上下文路径前缀为
/demo
server:
port: 8080
servlet:
context-path: /demo
主启动类SpringBootDemoHelloworldApplication
package com.xkcoding.helloworld;
import cn.hutool.core.util.StrUtil;
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;
/**
* <p>
* SpringBoot启动类
* </p>
*
* @package: com.xkcoding.helloworld
* @description: SpringBoot启动类
* @author: yangkai.shen
* @date: Created in 2018/9/28 2:49 PM
* @copyright: Copyright (c)
* @version: V1.0
* @modified: yangkai.shen
*/
@SpringBootApplication
@RestController
public class SpringBootDemoHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoHelloworldApplication.class, args);
}
/**
* Hello,World
* 传参示例:http://localhost:8080/demo/hello?who=felix
*
* @param who 参数,非必须
* @return Hello, ${who}
*/
@GetMapping("/hello")
// 从路径中提取who字段内容
public String sayHello(@RequestParam(required = false, name = "who") String who) {
if (StrUtil.isBlank(who)) {
// 如果没有传参数,默认打印Hello, World
who = "World";
}
// 使用hutool工具包格式化文本,将占位符{}转换为对应的参数
return StrUtil.format("Hello, {}!", who);
}
}
测试
- 在路径中输入:
http://localhost:8080/demo/hello?who=felix
,得到以下输出