SpringBoot入门(第二篇) 环境搭建,创建我的第一个程序HelloWord。
环境准备:
- jdk1.8:java version "1.8.0_231",详见
- maven3.x:maven3.3以上版本,详见
- IDEA2021:IntelliJ IDEA 2021.1.1 x64,详见
Spring Boot 之HelloWorld
功能:实现从web端发送接口请求,服务端收到请求并响应
1、使用Spring Initializr创建
1)File > New > Project
2)选中Spring Initializr,填写Artifact(项目名称)、Group(项目组织)、以及Package name(包名),和选择Loacation(项目存放的目录),点击Next
3)因为创建的是一个Web项目,所以引入Spring Web的相关组件,点击Finish
创建完成后的目录结构:
-
代码目录:src/main/java/com.cavan.helloword
HellowordApplication启动类 -
资源目录:resource
static:静态资源(jss css 图片 音频 视频)
templates:模板文件(模板引擎freemarker thymeleaf 默认不支持jsp)
application.properties:Spring boot默认的应用外部配置文件 -
单元测试目录:test/java/com.cavan.helloword
-
配置文件:pom.xml
该文件用于管理源代码、打包方式、项目的依赖关系等等。
2、编写代码
通常,我们使用三层结构来编写。
应用层(Controller)、服务层(Service)、数据层(Dao)
我们在controller层增加HelloWorld类:
package com.cavan.helloword.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @program: helloword
* @description:
* @author: cavan
* @create: 2021-11-28 10:31
*/
@RestController
@RequestMapping(value = "")
public class HelloWord {
@GetMapping(value = "hello")
public String hello() {
return "hello world";
}
}
并在application.properties配置文件中修改服务端口:
server.port=8888
3、运行
3.1在本地idea运行
1)运行主程序 Run > Run 'HellowordApplication'
2)chorme浏览器访问http://localhost:8080/hello
3.2在Linux环境运行
1)通过mvn clean package 命令打包成helloword-0.0.1-SNAPSHOT.jar;
2)将jar包上传到/root目录下,使用java -jar helloword-0.0.1-SNAPSHOT.jar运行项目代码
3)使用curl访问服务,curl http://localhost:8888/hello
本文代码Gitee链接:https://gitee.com/cavan2021/springboot/tree/master/helloword