springboot怎么监听端口请求

1224
2023/9/15 17:34:17
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Spring Boot中,可以使用内置的Tomcat服务器来监听端口请求。以下是一种常见的方式:

  1. 在pom.xml文件中添加Tomcat的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 创建一个Spring Boot的启动类,并添加@SpringBootApplication注解:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
  1. 在启动类中定义一个Controller类,用于处理请求:
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
  1. 在application.properties或application.yml文件中配置监听的端口号:
server.port=8080
  1. 运行MyApplication类的main方法,启动Spring Boot应用。

现在,你可以通过访问http://localhost:8080/hello来测试请求,并获取到"Hello, Spring Boot!"的响应结果。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: springboot框架搭建的步骤是什么