一尘不染

Spring MVC VersionResourceResolver / ContentVersionStrategy在JSP中无法正常工作

jsp

我有一个Spring
MVC(4.3.0)应用程序,并已向ResourceHandlerRegistry注册了带有添加的ContentVersionStrategy的VersionResourceResolver。我启用了ResourceUrlEncodingFilter。

    @Bean
    public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
        return new ResourceUrlEncodingFilter();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        boolean devMode = this.env.acceptsProfiles("local");
        //boolean useResourceCache = !devMode;
        Integer cachePeriod = devMode ? 0 : (60 * 60 * 24 * 365); //If dev clear cache else 1 year

        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/")
                .setCachePeriod(cachePeriod)
                .resourceChain(false)
                .addResolver(new VersionResourceResolver()
                    .addContentVersionStrategy("/**"))
                .addTransformer(new AppCacheManifestTransformer());
}

当我使用c:url或spring:url标记访问JSP页面上/ resources中的任何内容(JS,图像,CSS等)时,“版本化”
URL不显示(意味着:URL中没有哈希代码) 。例:

<link href="<c:url value="/resources/css/views/login.css" />" rel="stylesheet">

检查页面时,将产生:/myapp/resources/css/views/login.css作为URL字符串。

但是,如果我在Controller中使用ResourceURLProvider,我 在URL中看到哈希代码:

@Autowired
private ResourceUrlProvider mvcResourceUrlProvider;

@RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String projectBaseRedirect() {

    logger.debug("js =  '" + this.mvcResourceUrlProvider.getForLookupPath("/resources/js/views/overview.js") + "'");
    logger.debug("css =  '" + this.mvcResourceUrlProvider.getForLookupPath("/resources/css/views/overview-page.css") + "'");

    return "redirect:/admin/overview";
}

日志消息产生以下内容:

2016-07-09 11:47:19   DEBUG AdminLoginController:35 - js =  '/resources/js/views/overview-36d1ff98d627d92a72d579eca49dbd8a.js'
2016-07-09 11:47:19   DEBUG AdminLoginController:36 - css =  '/resources/css/views/overview-page-d47f10e5bcf0fdd67bd8057479b523f0.css'

为什么这在控制器中有效,但在我的JSP页面上却无效?

我也在使用Spring Security(4.1.0)…


阅读 565

收藏
2020-06-10

共1个答案

一尘不染

由于您的示例中缺少它,因此您的项目中也可能缺少它。您需要使用资源的模板引擎。如果是JSP,请注册一个过滤器:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Bean
  public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
    return new ResourceUrlEncodingFilter();
  }
}

或将过滤器注册bean与该过滤器一起使用:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
    final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new ResourceUrlEncodingFilter());
    filterRegistrationBean.addUrlPatterns("/*");
    return filterRegistrationBean;
  }
}
2020-06-10