Spring Boot 单页应用程序 - 将每个请求转发到 index.html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38783773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:09:19  来源:igfitidea点击:

Spring boot single page application - forward every request to index.html

springspring-mvcspring-boot

提问by Christoph

I have a Spring Boot (v1.3.6) single page application (angular2) and i want to forward all request to the index.html.

我有一个 Spring Boot (v1.3.6) 单页应用程序 (angular2),我想将所有请求转发到index.html.

A request to http://localhost:8080/index.htmlis working (200 and i get the index.html) but http://localhost:8080/homeis not (404).

http://localhost:8080/index.html的请求正在工作(200,我得到了 index.html)但http://localhost:8080/home不是(404)。

Runner.class

Runner.class

@SpringBootApplication
@ComponentScan({"packagea.packageb"})
@EnableAutoConfiguration
public class Runner {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext run = SpringApplication.run(Runner.class, args);
    }
}

WebAppConfig.class

WebAppConfig.class

@Configuration
@EnableScheduling
@EnableAsync
public class WebAppConfig extends WebMvcConfigurationSupport {

    private static final int CACHE_PERIOD_ONE_YEAR = 31536000;

    private static final int CACHE_PERIOD_NO_CACHE = 0;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.setOrder(-1);
        registry.addResourceHandler("/styles.css").addResourceLocations("/styles.css").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
        registry.addResourceHandler("/app/third-party/**").addResourceLocations("/node_modules/").setCachePeriod(CACHE_PERIOD_ONE_YEAR);
        registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(CACHE_PERIOD_NO_CACHE);
        registry.addResourceHandler("/systemjs.config.js").addResourceLocations("/systemjs.config.js").setCachePeriod(CACHE_PERIOD_NO_CACHE);
        registry.addResourceHandler("/**").addResourceLocations("/index.html").setCachePeriod(CACHE_PERIOD_NO_CACHE);
    }

}

styles.css, /app/third-party/xyz/xyz.js,.. are working (200 and i get the correct file). Only /**to index.htmlis not working.

styles.css, /app/third-party/xyz/xyz.js,.. 正在工作(200 并且我得到了正确的文件)。只有/**index.html不起作用。

回答by Jean Marois

You can also add a forwarding controller like:

您还可以添加一个转发控制器,如:

@Controller
public class ForwardingController {
    @RequestMapping("/{path:[^\.]+}/**")
    public String forward() {
        return "forward:/";
    }
}

The first part {path:[^\\.]+}matches one or more of any character other than .. This makes sure request for a file.extdoesn't get handled by this RequestMapping. If you need to support sub-paths to also be forwarded, put /**outside of the {...}.

第一部分{path:[^\\.]+}匹配一个或多个除.. 这可确保file.ext此 RequestMapping 不会处理对 a 的请求。如果您需要支持子路径也被转发,放/**外面{...}

回答by rhinds

Without looking at logs I'm not entirely sure why its not being mapped correctly, however if you want to map URLs to a view (HTML) then you will probably be better off using the viewControllermechanism spring provides http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-config-view-controller. e.g.

在不查看日志的情况下,我不完全确定为什么它没有被正确映射,但是如果您想将 URL 映射到视图(HTML),那么您可能最好使用viewControllerspring 提供的机制http://docs.spring。 io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-config-view-controller。例如

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("home");
  }

}

(taken from spring docs linked above - this is how you should map a url to a view rather than re-purposing the mapping for static resources.)

(取自上面链接的 spring 文档 - 这是您应该如何将 url 映射到视图,而不是重新使用静态资源的映射。)

I'm not sure if there is any kind of suffix filtering for the resource mapping - e.g. I don't know how spring decides to map requests to the ResourceHttpRequestHandler- have you tried (just to confirm or deny) whether something like http://localhost:8080/home.htmlamps to anything?

我不确定资源映射是否有任何类型的后缀过滤 - 例如,我不知道 spring 如何决定将请求映射到ResourceHttpRequestHandler- 您是否尝试过(只是为了确认或拒绝)是否像http://本地主机:8080/home.html放大器到任何东西?

It's also possible that the html mapping you have defined above is just being ignored and the index.html is just working because of Spring-Boot's default home page behaviour: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java#L108

由于 Spring-Boot 的默认主页行为,您在上面定义的 html 映射也有可能被忽略,而 index.html 正在工作:https: //github.com/spring-projects/spring-boot/blob /master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java#L108

回答by Flo

This one didn't work for me:

这个对我不起作用:

return "forward:/";

Thanks to Spring MVC @RestController and redirectI found a nicely working solution:

感谢Spring MVC @RestController 和重定向,我找到了一个很好的解决方案:

@RequestMapping(value = "/{[path:[^\.]*}")
public void redirect(HttpServletResponse response) throws IOException {
    response.sendRedirect("/");
}

回答by Ronny Shibley

I had the same problem and the following worked for me. My html files are inside src/main/resources/static/app

我遇到了同样的问题,以下对我有用。我的 html 文件在 src/main/resources/static/app 里面

The key was to remove @EnableWebMvc and add "classpath:/static/app/" to addResourceLocations! Hope this helps.

关键是删除@EnableWebMvc 并将“classpath:/static/app/”添加到addResourceLocations!希望这可以帮助。

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        "classpath:/META-INF/resources/", "classpath:/resources/",
        "classpath:/static/","classpath:/static/app/", "classpath:/public/" };

@Bean
public WebMvcConfigurer webMvcConfigurer() {
    return new WebMvcConfigurerAdapter() {

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!registry.hasMappingForPattern("/webjars/**")) {
                registry.addResourceHandler("/webjars/**").addResourceLocations(
                        "classpath:/META-INF/resources/webjars/");
            }
            if (!registry.hasMappingForPattern("/**")) {
                registry.addResourceHandler("/**").addResourceLocations(
                        CLASSPATH_RESOURCE_LOCATIONS);
            }
        }


        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            // forward requests to /admin and /user to their index.html
            registry.addViewController("/portal").setViewName(
                    "forward:/app/index.html");
        }
    };
}