2014-09-04 2 views
4

У меня есть следующие thymeleaf HTML страницы:Spring загрузки не сервировки Статическое содержимое с Thymeleaf

<head th:fragment="header"> 

    <meta charset="utf-8" /> 
    <link rel="stylesheet" href="../../css/main.css" th:href="@{/css/main.css}" /> 
    <title th:text="#{device.page.title}">Title</title> 
</head> 

<body> 
<div> 
    <h1 th:text="#{device.table.caption}"></h1> 
    <hr class="fineline"/> 
    Select devices using the checkboxes, you can update the client version or add client commands. 
    <form action="#" th:action="@{/devices/modify}" th:object="${deviceCommand}" method="post"> 
    <table border="0" cellpadding="0" cellspacing="0" class="touchTable"> 
     <!--<thead> --> 
      <tr> 
       <td scope="col" th:text="#{device.check.label}">Select</td> 
       <td width="300" scope="col"><span th:text="#{device.id.label}"></span>&nbsp;(<span th:text="#{device.retailer.name.label}"></span>)</td> 
       <td scope="col" th:text="#{device.current.label}">Curr Version</td> 
       <td scope="col" th:text="#{device.next.label}">Next Version</td> 
       <td scope="col" th:text="#{device.commands.label}">Commands</td> 
      </tr> 
     <!--</thead>--> 
     <!--<tbody> --> 
      <tr th:each="d : ${devices}"> 
       <td><input type="checkbox" th:field="*{deviceModificationIds}" th:value="${d.id}"/></td> 
       <td><span th:text="${d.id}"></span>&nbsp;(<span th:text="${d.retailerName}"></span>)</td> 
       <td th:text="${d.currentClientVersion}">Washington</td> 
       <td th:text="${d.nextClientVersion}">gwash</td> 
       <td th:text="${d.commands}">gwash</td> 
      </tr> 
      <tr> 
       <td colspan="2"></td> 
       <td><span th:text="#{device.change.version.label}"></span><br/><input type="text" th:field="*{newVersion}"/></td> 
       <td><span th:text="#{device.add.command.label}"></span><br/><input type="text" th:field="*{newCommand}"/></td> 
       <td><br/><button type="submit" th:text="#{device.modify.action.button}">Action</button></td> 
      </tr> 
     <!--</tbody> --> 
    </table> 
    </form> 


</div> 
</body> 

Проблема заключается с помощью CSS стилей. В основном весной, кажется, не быть в состоянии найти его, despit меня поместить файл в /resources/static/css/main.css

Это возвращает ошибку (в журнале):

o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/css/main.css] in DispatcherServlet with name 'dispatcherServlet' 

Теперь DOCO все говорит, что весна загрузки автоматически служить вещи/ресурсы/статические

Вот мой WebConfig:

@Configuration 
@ComponentScan("com.txxxxcorp.txxxxpoint.resource") 
@EnableWebMvc 
public class WebConfig { 

    @Bean 
    MultipartConfigElement multipartConfigElement() { 
     MultiPartConfigFactory factory = new MultiPartConfigFactory(); 
     factory.setMaxFileSize("4096KB"); 
     factory.setMaxRequestSize("4096KB"); 
     return factory.createMultipartConfig(); 
    } 

    @Bean 
    public ViewResolver viewResolver() { 
     ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); 
     templateResolver.setTemplateMode("XHTML"); 
     templateResolver.setPrefix("templates/"); 
     templateResolver.setSuffix(".html"); 

     SpringTemplateEngine engine = new SpringTemplateEngine(); 
     engine.setTemplateResolver(templateResolver); 

     ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 
     viewResolver.setTemplateEngine(engine); 

     String[] excludedViews = new String[]{ 
      "/resources/static/**"}; 
     viewResolver.setExcludedViewNames(excludedViews); 

     return viewResolver; 
    } 

    @Bean 
    public EmbeddedServletContainerCustomizer servletContainerCustomizer() { 
     return new EmbeddedServletContainerCustomizer() { 
      @Override 
      public void customize(ConfigurableEmbeddedServletContainer servletContainer) { 
       ((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
         new TomcatConnectorCustomizer() { 
          @Override 
          public void customize(Connector connector) { 
           AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); 
           httpProtocol.setCompression("on"); 
           httpProtocol.setCompressionMinSize(256); 
           String mimeTypes = httpProtocol.getCompressableMimeTypes(); 
           String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE; 
           httpProtocol.setCompressableMimeTypes(mimeTypesWithJson); 
          } 
         } 
       ); 
      } 
     }; 
    } 

    @Bean 
    public ResourceBundleMessageSource messageSource() { 
     ResourceBundleMessageSource source = new ResourceBundleMessageSource(); 
     source.setBasename("messages"); 
     return source; 
    } 

По какой-то причине, редактор не позволяет мне вставить (IntelliJ, Maven и Spring Boot не согласны с этим, поскольку он компилируется и работает), будьте уверены, что я разрешил путь /css/main.css пройти через

Does кто-нибудь знает, почему я не могу разрешить файл css?

+0

Есть ли какая-то особая причина, что вы не используя '@ EnableAutoConfiguration', и вы настраиваете Spring MVC самостоятельно? Я уверен, что Spring Boot не обслуживает статический контент, потому что у вас отключена вся автоматическая настройка. – geoand

+0

У меня есть @EnableAutoConfiguration на стартере приложения, я думал, что это единственное место, в котором вы нуждались? –

+0

Хорошо, я вижу. Однако тот факт, что у вас есть '@ EnableWebMvc', отключит автоконфигурацию MVC. См. Http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration – geoand

ответ

10

Тот факт, что вы использовали @EnableWebMvc, отключает автоконфигурацию MVC Spring Boot (и, следовательно, обработку статических ресурсов).

Чтобы включить обработку статических ресурсов, лучшим решением является удаление @EnableWebMvc, и пусть Spring Boot сделает то, что он делает лучше всего - автоконфигурирование.

После изменения вы должны сделать некоторые регрессивное тестирование, чтобы убедиться, что ничего другого сломал

+0

Если вы используете весеннюю безопасность, вам нужно добавить «/ css/**» в antMatchers(). AllowAll() – fjkjava

+0

@fjkjava Это правда. Однако не было упомянуто о безопасности Spring в вопросе, поэтому я не затронул ничего подобного в ответе – geoand

1

@ Ответ geoand является правильным, статический ресурс вашего приложения, выключают, как вы используете @enablWebMvc. поэтому любой CSS файл, который вы использовали здесь были разобраны thyemeleaf, вы должны объявить класс inheritted в WebMvcAutoConfigurationAdapter и переопределить метод addResourceHandlers, код может быть, как показано ниже:

@Configuration 
    @ComponentScan("com.txxxxcorp.txxxxpoint.resource") 
    @EnableWebMvc 
    public class WebConfig extends WebMvcConfigurerAdapter { 

@Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     String[] STATIC_RESOURCE = {"/","classpath:/","classpath:/META-INF/resources/", "classpath:/META-INF/resources/webjars/", 
       "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; 

     if (!registry.hasMappingForPattern("/**")) { 
      registry.addResourceHandler("/**").addResourceLocations(STATIC_RESOURCE); 
     } 
    } 

....................... 
} 
Смежные вопросы