跟着Spring官网学习(1): Spring Quickstart Guide

Spring官方网站原文地址:https://spring.io/quickstart

本文是在官方原文的基础上翻译并实操。

Spring Quickstart Guide

What you'll build

你将建立一个经典的“Hello World!”终端,任何浏览器都可以连接到。你甚至可以告诉它你的名字,它会以更友好的方式回应。

What you'll need

集成开发环境(IDE)
流行的选择包括IntelliJ IDEA, Spring Tools, Visual Studio Code,或Eclipse等等
Java™开发工具包(JDK)
我们建议采用版本8或版本11的jdk。

Step 1: Start a new Spring Boot project

官方原文是使用https://start.spring.io/网页来创建SpringBoot项目,这里使用STS(Spring Tool Suite)来创建。

1. New --> Spring Starter Project

2. 勾选Spring Web

3. Finish后项目结构如下

Step 2: Add your code

src/main/java/com/example/demo下的 DemoApplication.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”的字符串参数,然后将该参数与代码中的单词“hello”结合起来。这意味着如果您在请求中将您的名字设置为“Amy”,那么响应将是“Hello Amy”。

@RestController注释告诉Spring这段代码描述了一个应该在web上可用的端点。@GetMapping(" /hello ")告诉Spring使用我们的hello()方法来应答发送到http://localhost:8080/hello地址的请求。

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

Spring web的默认端口是8080,可以在application.properties文件中添加 server.port=8083 来修改端口

Step 3: Try it

官方原文操作是,打开命令行终端并导航到包含项目文件的文件夹,通过执行以下命令来构建和运行应用程序:

MacOS/Linux:

./mvnw spring-boot:run

Windows:

mvnw spring-boot:run

这里直接使用STS运行Spring Boot App

打开浏览访问 http://localhost:8083/hello

试试在链接加上 ?name=Amy

原文地址:https://www.cnblogs.com/fangjb/p/14149534.html