2016-09-23 210 views
0

我試圖提供靜態資源(css文件)。 我已經註冊的位置和處理程序Spring MVC無法提供靜態資源

@Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/"); 
    } 
} 

所以Tomcat的記錄器顯示正確的映射到資源

映射的URL路徑[/資源/ **]到類型[類org.springframework的處理程序.web.servlet.resource.ResourceHttpRequestHandler]

當瀏覽器呈現視圖時,檢查器顯示嘗試獲取靜態資源的404錯誤。

enter image description here

AppInitializer.java

@Configuration 
@ComponentScan("com.learning") 
@EnableWebMvc 
public class ApplicationInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer { 

    private final Logger LOGGER = Logger.getLogger(ApplicationInitializer.class.getName()); 
    public static final String DISPATCHER_SERVLET_NAME = "dispatcher"; 

    @Autowired 
    private ApplicationContext applicationContext; 

    public ApplicationInitializer() { 
    } 

    //region Context Initialization Area 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     WebApplicationContext springContext = getSpringApplicationContext(); 
     MyDispatcherServlet dispatcherServlet = new MyDispatcherServlet(springContext); 

     servletContext.addListener(new ContextLoaderListener(springContext)); 
     servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); 
     servletContext.getSessionCookieConfig().setHttpOnly(true); 

     ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, dispatcherServlet); 
     dispatcher.addMapping("/"); 
     dispatcher.setLoadOnStartup(1); 

    } 

    private WebApplicationContext getSpringApplicationContext() { 
     AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); 
     LOGGER.info(String.format("Registering springApplicationContext: %s", context)); 
     // Loads into container first 
     context.register(ApplicationInitializer.class); 
     LOGGER.info(String.format("Registration success of springApplicationContext: %s", context)); 
     return context; 
    } 
    //endregion 

    //region ViewResolver Region 
    @Bean 
    public ViewResolver viewResolver() { 
     //Runs after coontroller ends its execution. It receives the view name to be processed. 
     ThymeleafViewResolver resolver = new ThymeleafViewResolver(); 
     resolver.setTemplateEngine(templateEngine()); 
     resolver.setCharacterEncoding("UTF-8"); 
     return resolver; 
    } 

    @Bean 
    public TemplateEngine templateEngine() { 
     // Processes the template 
     SpringTemplateEngine engine = new SpringTemplateEngine(); 
     engine.setEnableSpringELCompiler(true); 
     engine.setTemplateResolver(templateResolver()); 
     return engine; 
    } 

    private ITemplateResolver templateResolver() { 
     //Resolves templates with provided preffix and suffix 
     SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); 
     resolver.setApplicationContext(applicationContext); 
     resolver.setPrefix("/WEB-INF/views/"); 
     resolver.setSuffix(".html"); 
     resolver.setTemplateMode(TemplateMode.HTML); 
     return resolver; 
    } 
    //endregion 

    //region ResourceHandler Region 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/"); 
    } 
    //endregion 
} 

的Hello.html

h1 { 
 
    color: red; 
 
    text-align: center; 
 
}
<!DOCTYPE html> 
 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title></title> 
 
    <link rel="stylesheet" href="/resources/css/MyCss.css" th:href="@{/resources/css/MyCss.css}"/> 
 
</head> 
 
<body> 
 
    <h1 th:text="'Hello ' + ${name}">Hello World</h1> 
 
</body> 
 
</html>

它應該顯示爲正在運行的片段。B如我所說,該應用程序無法找到並加載資源。

Log File

classpath

enter image description here

enter image description here

任何幫助嗎?

+0

把你的日誌來調試或跟蹤,告訴我們Spring吐出了什麼。 –

+0

完成,檢查我的編輯。 @SotiriosDelimanolis –

+0

那些日誌顯示_Successfully completed request_。 –

回答

1

http://localhost:8080/resources/css/MyCss.css

你缺少web應用程序名稱:

http://localhost:8080/webapp_name/resources/css/MyCss.css

在您:link rel="stylesheet" ...

使用春URL標記,以解決您的網址更好。

這裏是我如何使用導入bootstrap.min.css:

<link rel="stylesheet" href='<spring:url value="/resources/bootstrap/bootstrap.min.css"/>' type="text/css" /> 

不要忘記添加標籤庫,就像這樣:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
+0

我正在使用Thymeleaf和.html文件來查看視圖,我怎樣才能在這些文件中引用taglib? 當我按照您指出的方式使用導入時,我在瀏覽器檢查器中看到以下錯誤:2http:// localhost:8080 /%3Cspring:url%20value =%22/resources/css/MyCss.css%22 /% 3E無法加載資源:服務器響應的狀態爲404 –

+0

我對Thymeleaf並不熟悉,但從wiki中我看到它是基於servlet的,而JSP文件基本上是Servlet文件,它在Tomcat的Jasper組件轉換成servlet後。你想把這個taglib作爲一個指令添加到一個JSP文件中。 –