Spring在具有通配符控制器路由的同时提供静态内容 [英] Spring serving static content while having wildcard controller route

查看:250
本文介绍了Spring在具有通配符控制器路由的同时提供静态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是使用前端上的主干和后端上的spring框架构建的.它是一个单独的html应用程序.路由是由骨干网处理的,因此我有一个具有以下结构的后端路由:

My application is build using backbone on frontend and spring framework on backend. It is a single html application. Routes are handled by backbone, so I have a backend route with the next structure:

@RequestMapping(value="/**", method=RequestMethod.GET)
public String Pages()
{
    return "index";
}

将所有内容都指向我的index.html.问题是静态内容 文件也指向此路由,我不希望这样做.我试图 通过重写addResourceHandler方法来配置WebMvcConfigurerAdapter 静态内容,但无效.

To point everything to my index.html. The thing is that the static content files are pointed to this route too, and I don't want this. I've tried to config WebMvcConfigurerAdapter by overriding addResourceHandler method for static content, but it doesn't work.

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("/resources/js");
    }
}

如何将除/js/**和/assets/**之外的所有路径都指向我的index.html?

How can I point every route to my index.html except /js/** and /assets/** ?

谢谢

推荐答案

第一件事是,映射到/**的控制器方法将优先于任何资源请求.您可以通过增加ResourceHandlerRegistry的优先级来解决此问题.在StaticResourceConfigurationaddResourceHandlers方法中将呼叫添加到registry.setOrder(Ordered.HIGHEST_PRECEDENCE):

The first thing is that your controller method that's mapped to /** will be taking priority over any resource requests. You can address this by increasing the precedence of ResourceHandlerRegistry. Add a call to registry.setOrder(Ordered.HIGHEST_PRECEDENCE) in the addResourceHandlers method of StaticResourceConfiguration:

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        registry.addResourceHandler("/js/**").addResourceLocations("/resources/js");
    }
}

第二件事是,默认情况下,Spring Boot默认为您配置两个资源处理程序,即

The second thing is that, by default, Spring Boot configures two resource handlers for you by default, one mapped to /** and one mapped to /webjars/**. Due to the change described above, this will now take priority over the method in your controller that's also mapped to /**. To overcome this, you should turn off default resource handling via a setting in application.properties:

spring.resources.addMappings=false

这篇关于Spring在具有通配符控制器路由的同时提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆