gpt4 book ai didi

java - 使用 @EnableWebMvc 和 WebMvcConfigurerAdapter 进行静态资源定位的 Spring MVC 配置导致 "forward:"和 "redirect:"出现问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:38 24 4
gpt4 key购买 nike

我有一个用于 web 的 Spring Boot hello world 和一些配置混淆:

Spring 版本:1.2.6.RELEASE

我的项目结构:

enter image description here

我需要提供一些静态内容,所以我决定在一些自定义 WebConfig 类中重新定义此类内容的源目录(用于研究目的):

@EnableWebMvc 的 Javadoc 说:

Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport

To customize the imported configuration, implement the interface WebMvcConfigurer or more likely extend the empty method base class WebMvcConfigurerAdapter and override individual methods, e.g.:

于是下一个配置类诞生了:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/r/**").addResourceLocations("classpath:/static/r/");
registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/r/favicon.ico");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/r/diploma/index.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
super.addViewControllers(registry);
}
}

如果运行应用程序并尝试访问 http://localhost:8080/我得到下一个异常:

javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'

但是 如果我从我的 WebConfig 中删除 @EnableWebMvc,我会在浏览器中得到我的 index.html。那么这种行为的原因是什么?

实际上,我有一个生产项目,我以此为例进行研究,它在 WebConfig 上同时具有 @EnableWebMvcWebMvcConfigurerAdapter

最佳答案

您应该添加一个 ViewResolver 来解析您在 WebConfig 中的 View ,如下所示:

@Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}

当您添加 @EnableWebMvc 时,您将关闭所有 spring boot 的 web 自动配置,它会自动为您配置此类解析器。通过删除注释,自动配置将再次打开,自动配置的 ViewResolver 解决了这个问题。

关于java - 使用 @EnableWebMvc 和 WebMvcConfigurerAdapter 进行静态资源定位的 Spring MVC 配置导致 "forward:"和 "redirect:"出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981198/

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