gpt4 book ai didi

java - 带有 React UI 的 Spring 应用程序-应用@EnableWebMvc 时如何服务?

转载 作者:行者123 更新时间:2023-12-04 14:05:55 24 4
gpt4 key购买 nike

所以我有一个 React 应用程序,我想从我的 Spring 应用程序 (ala this blog) 提供服务。作为我的 gradle 构建任务的一部分,我运行 npm build 命令并将生成的文件复制到 /build/resources/main/static。这工作正常,我可以在 mysite.com/index.html 访问我的应用程序,但我想更精细地控制谁可以访问。因此,我将 @EnableWebMvc 应用于我的应用程序,但从那里,我似乎无法让我的 API Controller 实际为构建目录中的 View 提供服务。似乎无论我把它放在哪里,它都不喜欢直接从/build 提供服务。有什么方法可以使它起作用吗?

处理程序看起来像:

@Controller
class MyController {
@RequestMapping("/")
fun index(): String {
return "index"
}
}

最佳答案

Spring Boot documentation 中所示,你不需要——事实上,不推荐——在使用 Spring Boot 时使用 @EnableWebMvc。他们在描述 Spring MVC 自动配置时声明:

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

和:

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

在指南中,他们在描述 static content handling 时继续:

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

在你的例子中,按照这个建议,你可以用类似的东西来指示静态资源处理位置(抱歉,我不精通 Kotlin,原谅我用 Java 写这个例子):

@Controller
public class MyController implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static")
;
}

@GetMapping(path = "/")
public String index() {
return "index";
}
}

请根据您的需要调整 addResourceHandlers 中的路径。

您当然可以将此方法放在临时的 @Configuration 中。

话虽如此,如果您说粒度是指安全性,那么您可以采取的最佳方法是配置 Spring Security 并提供必要的授权规则:请参阅 relevant documentation .

关于java - 带有 React UI 的 Spring 应用程序-应用@EnableWebMvc 时如何服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68539015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com