静态内容未在 Springboot 2.1.7.RELEASE 中提供



在我的 Springboot 应用程序中,即使从日志消息中看到的其余端点被正确命中,我也会收到以下 404 错误。

我有一个带有以下主类的 springboot 应用程序:-

package com.springbootbasic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootBasicApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootBasicApplication.class, args);
}
}

以下是控制器类:-

package com.springbootbasic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {
Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping("/hello")
public String home(Model model) {
logger.info("Rest endpoint /hello is being hit correctly.");
return "index.html";
}
@RequestMapping("/home")
@ResponseBody
public String response() {
logger.info("Rest endpoint /home is being hit correctly.");
return "Very well done the rest end point is working fine.";
}
}

上述两个类在同一个包中,HomeController 用 @Controller 而不是@RestController注释。

在 eclipse 的 src/main/public source 文件夹中,我创建了以下索引.html文件。

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome from Home</title>
</head>
<body>
<h2>Hello World!</h2>
</body>
</html>

当我点击网址时,在浏览器中 http://localhost:8080/hello 我收到以下错误:-

There was an unexpected error (type=Not Found, status=404).
No message available

但日志消息是:-

2019-08-28 20:22:38.953  INFO 20864 --- [nio-8080-exec-1] c.springbootbasic.HomeController   : Rest endpoint /hello is being hit correctly.
2019-08-28 20:22:52.179  INFO 20864 --- [nio-8080-exec-3] c.springbootbasic.HomeController   : Rest endpoint /home is being hit correctly.
2019-08-28 20:25:20.858  INFO 20864 --- [nio-8080-exec-6] c.springbootbasic.HomeController   : Rest endpoint /hello is being hit correctly.

如何解决这个问题?

问题是模板的名称。模板的名称是索引,如果您点击 http://localhost:8080/,则可以看到您的页面。我遇到了同样的问题,如果您重命名索引.html应该没问题。我不知道为什么会发生这种情况,它可能与 spring-boot 嵌入式服务器有关。

编辑:从 https://spring.io/guides/gs/serving-web-content/

索引.html资源是特殊的,因为它被用作"欢迎" 页面",如果存在,这意味着它将作为根目录提供 资源,即在 http://localhost:8080/

希望这有帮助。

您应该创建内部视图解析程序并将其添加到配置适配器中

相关内容

最新更新