java - 配置要在 Spring Boot 应用程序上提供的 React

标签 java spring

到目前为止,我一直在为我的 Spring boot 应用程序编写一堆端点,没有 html UI 端。现在,我想提供包含 react 代码的 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.添加了一个rest Controller 端点:

@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 文件。

最佳答案

Spring Boot可以自动处理静态文件(按照惯例),只需将你所有的html、js、css等文件放到src/main/resources/static,去掉你的ViewResolver和Controller对于 '/' 它将起作用,index.html 也将被 Spring Boot 映射到 /

除此之外,您当然可以通过在 @RestController 上使用正确的 @RequestMapping 来创建带有 api 前缀的 REST 端点

关于java - 配置要在 Spring Boot 应用程序上提供的 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47381362/

相关文章:

java - 如何使用 SharedPreferences 保存 SparseBooleanArray?或者还有其他选择吗?

java - 使用 Spark 和 Cassandra Java 驱动程序时检测到 Guava 问题 #1635

database - Flyway 无法实例化 jdbc 驱动程序

java - Spring bean 测试

java - 如何在 Spring Boot 中创建 JDBC TokenStore?

java - 我的数独回溯算法仅在部分时间有效,有人可以帮助我改进它吗?

java - 类型推断和目标类型

java - 在 Java3D 中更改枢轴点

spring - JHipster Spring Boot 应用程序中超过了高磁盘水印 [90%]

java - 如何使用 RestTemplate 禁用编码