Index / Spring

Spring 开篇,创建第一个 Web 项目 Hello World

原文:https://ichochy.com/posts/spring/20210525.html

学习 Java,就离不开 Spring ,现在就用 Spring 框架快速创建一个 WEB 项目,欢迎来到我的世界 Hello World。

开发工具

创建项目

打开 IDEA 创建新项目 New Project,使用 start.spring.io 快速构建 16226365527086133

添加 Spring Web 依赖,finish 创建项目 16226367387048384

项目目录

├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── ichochy
        │           └── example
        │               ├── ExampleApplication.java
        │               └── hello
        │                   └──HelloWorldController.java
        └── resources
            ├── application.properties
            ├── static
            └── templates

编写项目

创建控制器 HelloWorldController

package com.ichochy.example.hello;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

创建启动器 ExampleApplication

/*
 * Copyright (c) 2021 iChochy
 * URL:https://ichochy.com
 * Date:2021/06/09 22:07:09
 */

package com.ichochy.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

@SpringBootApplication 注释,包如下注解的合集:

运行项目

Dubug 运行项目,启动成功后可以看到默认端口号为8080 16226399326197735

浏览器访问 http://localhost:8080/hello,Web 项目默认返回 Hello World 16226401256157126

添加 name 参数访问 http://localhost:8080/hello?name=iChochy 16226436648645837

GitHub

https://github.com/iChochy/Example

引用