【发布时间】:2021-08-26 01:06:56
【问题描述】:
我是springboot的新手。我有一个如下所示的控制器类,
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@RequestMapping("/hello")
public String getHi() {
return "Hi";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
控制台,
Starting service [Tomcat]
Starting Servlet engine: [Apache Tomcat/9.0.46]
Initializing Spring embedded WebApplicationContextRoot WebApplicationContext: initialization completed in 626 ms
Tomcat started on port(s): 8080 (http) with context path ''
运行项目后,我尝试在浏览器中打开“localhost:8080/hello”,但我的 localhost 连接被拒绝。在控制台中,我可以看到,Tomcat 服务器以 8080 端口启动。 提前致谢。
更新 我通过在主类中添加以下行解决了我的问题,
@Autowired
Controller controller;
【问题讨论】:
-
在
@RequestMapping旁边添加@GET。 -
@randytan 我试过这样,
@RequestMapping (value ="/hello",method = RequestMethod.GET)但没有变化 -
检查端口
8080是否未被其他应用程序使用。或添加server.port=8082以使用此 url 在另一个端口上测试您的应用程序:localhost:8082/hello -
@HarryCoder 我尝试使用 8082 端口。这次我得到了“whitelabel error page”
-
这个链接可以回答你的问题:stackoverflow.com/questions/49034254/…
标签: java spring-boot httprequest spring-restcontroller request-mapping