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

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

开发工具

  • IDEA: 2021.1.2
  • Java: 1.8
  • Spring Boot: 2.5

创建项目

打开 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);
    }
}
  • @RestController 注解,告诉 Spring 该类(HelloWorldController)为请求控制器
  • @GetMapping(“/hello”) 注解,告诉 Spring 该方法(hello)来响应 http://localhost:8080/hello 的 get 请求。
  • @RequestParam 注解,告诉 Spring 该参数(name)为自定义请求参数,默认值为 “World”。

创建启动器 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 注释,包如下注解的合集:

  • @Configuration:将类标记为应用程序配置类
  • @EnableAutoConfiguration:告诉 Spring Boot 根据类路径自动启用配置
  • @ComponentScan:告诉 Spring 在com.ichochy.example当前包中查找组件、配置、服务和控制器

运行项目

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

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

16226401256157126

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

16226436648645837

GitHub

https://github.com/iChochy/Example

引用

相关文章

源文https://ichochy.com/posts/20210525.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值