在 Spring Boot 或一般 Spring MVC 应用程序中用于以下场景:
可以从使用自定义 ResourceHandlerRegistry 注册的位置提供静态文件。我们有一个静态资源index.html,它可以在localhost:8080/index.html访问。我们只想将localhost:8080/请求重定向到localhost:8080/index.html,可以使用以下代码。
package in.geekmj.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/index.html");
}
}
现在访问localhost:8080/将重定向到localhost:8080/index.html