2017-05-26 107 views
1

我有一个Spring MVC 4.2.x项目。我通过XML基于配置文件中配置它:Webjars-locator不支持基于XML的Spring MVC 4.2.x配置?

<servlet> 
    <servlet-name>foo</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/context.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

context.xml文件我已经配置资源和annotation-driven模式:

<mvc:resources mapping="/webjars/**" location="/webjars/"/> 
<mvc:annotation-driven/> 

,一切工作正常,除了一两件事:webjars-locator - Webjars定位器没有按根本不工作


我已经开始看到Spring MVC来源,以了解发生了什么错误,并发现,webjars-locator作品通过WebJarsResourceResolver类,它的对象是在ResourceChainRegistration.getResourceResolvers()类方法添加。

的全序列的样子:

WebMvcConfigurationSupport.resourceHandlerMapping() >>ResourceHandlerRegistration.getHandlerMapping() >>ResourceHandlerRegistration.getRequestHandler() >> ResourceChainRegistration.getResourceResolvers(),在那里它被添加为:

if (isWebJarsAssetLocatorPresent) { 
    result.add(new WebJarsResourceResolver()); 
} 

的问题,是基于XML配置的情况下,如上所述,该序列不被调用,都不使用WebMvcConfigurationSupport类。

而且,如果我添加

@EnableWebMvc 
@Configuration 
public class WebConfig { 
} 

到项目,WebMvcConfigurationSupport明显的作品,但在ResourceHandlerRegistration.getHandlerMapping()

protected AbstractHandlerMapping getHandlerMapping() { 
    if (registrations.isEmpty()) { 
     return null; 
    } 
... 
} 

registrations是空的!


毕竟,只有一个办法如何强行让春天增添WebJarsResourceResolver到解析器链是:

1)从context.xml

2删除<mvc:resources mapping="/webjars/**" location="/webjars/"/>)添加addResourceHandlersWebConfig

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry 
      .addResourceHandler("/webjars/**") 
      .addResourceLocations("/webjars/") 
      .setCachePeriod(3600) 
      .resourceChain(true) // !!! very important 
    ; 
} 

我的问题是:我做错了什么?为什么XML基础配置不会导致WebJarsResourceResolver被注册?

回答

1

假设上下文根路径为/ctx。用你的配置,资源路径为/webjars/RESOURCE实际上映射为/ctx/webjars/RESOURCE;与普遍预期相反,它应该被映射到/webjars/RESOURCE

基于Spring 4.2.x documentationan example similar issue,你需要映射/webjars/**到默认的调度的servlet为:

这使得映射的DispatcherServlet为“/”(因此重写容器的默认的Servlet的映射)同时仍允许静态资源请求由容器的默认Servlet处理。它使用“/ **”的URL映射和相对于其他URL映射的最低优先级来配置DefaultServletHttpRequestHandler。

这意味着添加以下应该解决这个问题:

<mvc:resources mapping="/webjars/**" location="/webjars/"> 
    <mvc:resource-chain> 
     <mvc:resource-cache /> 
    </mvc:resource-chain> 
</mvc:resources> 
<mvc:annotation-driven /> 
<mvc:default-servlet-handler /> 

另一个需要注意的是the example petclinic使用location="classpath:/META-INF/resources/webjars/"对此我不敢肯定与此有关webjars。

希望这会有所帮助。


通过@Andremoniy补充:

Spring 4它有稍微不同的标记:

<mvc:resources mapping="/webjars/**" location="/webjars/"> 
    <mvc:resource-chain resource-cache="true"/> 
</mvc:resources> 
+1

哈!所以问题只存在于',我不知道用XML指定它的明显方式,谢谢!这仍然没有回答为什么它不在webjar文档中描述的问题,但我接受它,因为它以所需的方式解决问题! – Andremoniy