springboot

springboot怎么监听端口请求

小亿
173
2023-10-11 17:34:17
栏目: 编程语言

在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!"的响应结果。

0
看了该问题的人还看了