【发布时间】:2018-05-03 01:02:34
【问题描述】:
到目前为止,我一直在为我的 Spring boot 应用程序编写一堆端点,没有 html UI 端。现在,我想提供包含反应代码的 HTML 文件和 js 文件。
当我访问 http://localhost:8443 时,我得到:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Nov 19 11:54:01 PST 2017
There was an unexpected error (type=Not Found, status=404).
Not Found
到目前为止我做了什么:
1.添加了一个扩展WebMvcConfigurerAdapter的Web配置类:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/resources/static/");
bean.setSuffix(".html");
return bean;
}
}
2.增加了一个休息控制器端点:
@RestController
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getdata() {
ModelAndView model = new ModelAndView("index");
return model;
}
}
我的项目中有myproject/src/main/resources/static/index.html 文件。
【问题讨论】:
-
您想在每个页面上都为 react 应用程序提供服务,还是需要保留一些 api-rest 端点?我的意思是你将如何区分 react 和 spring 端点,比如
/static/*用于 react 静态文件,/api/*用于 spring 端点,其余的/*用于 react index.html ? -
尝试从 Spring Boot 文档spring.io/guides/tutorials/react-and-spring-data-rest遵循本教程
-
如果我理解正确的话,您只想提供静态 html 和 js 文件。在这种情况下,您不需要 Controller 或 WebMvcConfigurerAdapter,只需将 html 和 js 文件放到 src/main/resources/static (您的 index.html 所在的位置),Spring Boot 就会自动为它提供服务。
-
@OleksandrShpota 教程建议安装 Thymleaf 包,而我不使用它的任何功能。
-
@varren 这正是我想做的。我想把所有其余的api放在
/api/*下,把所有与网络相关的东西放在/static/*下,并将/*路由到index.html。知道我该怎么做吗?