我正在构建一个简单的 Spring 应用程序,其目标是返回“Hello world”作为构建的基础。我昨晚按照 this 设置了一个干净的项目指南有效,现在我正在尝试将现有的项目引入相同的功能。
我有两个名为 ApplicationConfig.java
和 Controller.java
的文件,其任务是在点击某个 URL 时返回一个字符串。当我访问 localhost:8080 时,它会呈现我的 index.html,其中包含指向我希望返回字符串的 URL 的链接。当我访问 URL localhost:8080/home/greet
时,它返回 404。
我的ApplicationConfig.java
:
package application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
和我的Controller.java
package controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/home")
public class Controller {
@RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
据我所知 /home/greet/
应该生成一个仅显示“Hello”的页面,但事实并非如此。这是什么问题?
这是我的 pom.xml
以及我的项目结构,它们是否相关。
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<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>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
最佳答案
您的入口点类ApplicationConfig.java
位于application
包中,Controller.java
位于controller
包中。
SpringBoot 扫描 EntryPoint 类所在包(和子包)中的 Spring 组件。
因此,将 Controller 移至 application
或 application
下的任何嵌套包。
关于java - Spring 为有效 URL 生成 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39658067/