Spring boot thymeleaf布局[找不到带有URI * .css / * .js的HTTP请求的映射]

时间:2016-07-07 01:32:55

标签: thymeleaf

我使用thymeleaf和springboot来构建框架。并尝试使用百里香的布局模板。问题是使用 ThymeleafLayoutInterceptor 使用布局模板时。无法找到css和js的网址。

代码和配置如下:

您可以通过链接project view

查看项目布局
public class ThymeleafLayoutInterceptor extends HandlerInterceptorAdapter {

private static final String DEFAULT_LAYOUT = "layouts/default";

private static final String DEFAULT_VIEW_ATTRIBUTE_NAME = "view";

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    if (modelAndView == null || !modelAndView.hasView()) {
        return;
    }
    String originalViewName = modelAndView.getViewName();
    if (isRedirectOrForward(originalViewName)) {
        return;
    }
    modelAndView.setViewName(DEFAULT_LAYOUT);
    modelAndView.addObject(DEFAULT_VIEW_ATTRIBUTE_NAME,originalViewName);
}

private boolean isRedirectOrForward(String viewName) {
    return viewName.startsWith("redirect:") || viewName.startsWith("forward:");
}

}

@Configuration

公共类WebMvcConfig扩展了WebMvcConfigurationSupport {

@Override
protected void addInterceptors(InterceptorRegistry registry) {
    super.addInterceptors(registry);
    registry.addInterceptor(new ThymeleafLayoutInterceptor());
}

@Bean
public ServletContextTemplateResolver templateResolver(){
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/templates/views/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(1);
    return resolver;
}

@Bean
public SpringTemplateEngine templateEngine(){
    Set<IDialect> dialects = new HashSet<>();
    dialects.add(new LayoutDialect());
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    engine.setAdditionalDialects(dialects);
    return engine;
}

@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    resolver.setViewNames(new String[]{"*","springBootMvc/js/*","springBootMvc/css/*"});
    return resolver;
}

}

default.html中

&#13;
&#13;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
    <link th:href="@{/dataTable/media/css/jquery.dataTables.css}" rel="stylesheet" type="text/css"/>
    <link href="css/boot.css" rel="stylesheet" type="text/css"/>
    <link th:href="@{/bootstrap/css/bootstrap.min.css}" rel="stylesheet" type="text/css"/>

    <script th:src="@{/dataTable/media/js/jquery.js}" type="text/javascript" charset="utf8"/>
    <script th:src="@{/dataTable/media/js/jquery.dataTables.js}" type="text/javascript" charset="utf8"></script>
    <script th:src="@{/bootstrap/js/bootstrap.min.js}" type="text/javascript" charset="utf8"/>
    <script th:src="@{/js/boot.js}" type="text/javascript" charset="utf8"/>
</head>
<body>
<div th:raplace="fragments/header :: header">
    Header1
</div>
<div th:replace="${view} :: content">
    Content
</div>
<div th:replace="fragments/footer :: footer">
    Footer
</div>
</body>
</html>
&#13;
&#13;
&#13;

html的

application.yaml

&#13;
&#13;
server:
  context-path: /springBootMvc
  port: 8082

spring:
  profiles:
    active: test
  messages:
    basename: i18n
  devtools:
    restart:
      exclude: static/**
      additional-paths: src/main/
  thymeleaf:
    prefix: /templates/views/
    suffix: .html
&#13;
&#13;
&#13;

然后出现问题,我无法获得* .js和* .css的网址。 错误堆栈如下:

&#13;
&#13;
2016-07-07 09:22:08.427  WARN 9572 --- [nio-8082-exec-2] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/css/boot.css] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.452  WARN 9572 --- [nio-8082-exec-4] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/dataTable/media/js/jquery.js] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.454  WARN 9572 --- [nio-8082-exec-5] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/dataTable/media/css/jquery.dataTables.css] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.457  WARN 9572 --- [nio-8082-exec-6] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/bootstrap/css/bootstrap.min.css] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.461  WARN 9572 --- [nio-8082-exec-7] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/dataTable/media/js/jquery.dataTables.js] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.475  WARN 9572 --- [nio-8082-exec-3] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/bootstrap/js/bootstrap.min.js] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.740  WARN 9572 --- [nio-8082-exec-8] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/springBootMvc/js/boot.js] in DispatcherServlet with name 'dispatcherServlet'
2016-07-07 09:22:08.745 ERROR 9572 --- [nio-8082-exec-2] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]
&#13;
&#13;
&#13;

如果删除类WebMvcConfig,则可以找到那些* .css和* .js。但是布局模板不再起作用了。 screen with js, css but no header and footer

3 个答案:

答案 0 :(得分:9)

在扩展WebMvcConfigurerAdapter的类中,我使用@EnableWebMvc注释,关于相同的布局示例。

我删除了这个注释,布局工作原理相同,并且加载了css。

我希望这会有所帮助。

答案 1 :(得分:0)

最后,我通过阅读大量源代码解决了这个问题。我发现在我们的配置中缺少SimpleUrlHandlerMapping。我在代码中配置它。这可能有点复杂。如果有人有更简单的方法,欢迎与我联系!

@Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        Map<String, Object> map = new LinkedHashMap<>();
        ResourceHttpRequestHandler resourceHttpRequestHandler = new ResourceHttpRequestHandler();
        List<Resource> locations = new ArrayList<>();
        locations.add(new ServletContextResource(getServletContext(), "/"));
        locations.add(new ClassPathResource("META-INF/resources"));
        locations.add(new ClassPathResource("resources/"));
        locations.add(new ClassPathResource("static/"));
        locations.add(new ClassPathResource("public/"));
        resourceHttpRequestHandler.setLocations(locations);
        resourceHttpRequestHandler.setApplicationContext(getApplicationContext());

        List<ResourceResolver> resourceResolvers = new ArrayList<>();
        PathResourceResolver resourceResolver = new PathResourceResolver();
        resourceResolver.setAllowedLocations(new ServletContextResource(getServletContext(), "/"), new ClassPathResource("META-INF/resources"), new ClassPathResource("resources/"), new ClassPathResource("static/"), new ClassPathResource("public/"));
        resourceResolvers.add(resourceResolver);

        resourceHttpRequestHandler.setResourceResolvers(resourceResolvers);
        map.put("/**", resourceHttpRequestHandler);
        simpleUrlHandlerMapping.setUrlMap(map);
        ResourceUrlProvider resourceUrlProvider = new ResourceUrlProvider();
        Map<String, ResourceHttpRequestHandler> handlerMap = new LinkedHashMap<>();
        handlerMap.put("/**", resourceHttpRequestHandler);
        resourceUrlProvider.setHandlerMap(handlerMap);
        ResourceUrlProviderExposingInterceptor interceptor = new ResourceUrlProviderExposingInterceptor(resourceUrlProvider);
        simpleUrlHandlerMapping.setInterceptors(new Object[]{interceptor});
        return simpleUrlHandlerMapping;
    }

答案 2 :(得分:0)

默认情况下,spring boot资源应放在&#34; src / main / resources&#34;中,例如js和css文件应该放在/ static文件夹中 &#34; SRC /主/资源/静态/ CSS&#34;这同样适用于模板文件夹,如果你不需要任何特殊的东西,几乎不需要任何配置。 尝试运行您的应用程序并检查日志记录,Spring记录所有映射,然后您可以检查默认映射是什么。

当我回家时,我会附上我的项目层次结构。