2014-02-22 74 views
2

我想從我的jsp頁面使用css文件,但頁面沒有看到css代碼。如何在jsp頁面中使用css

這是我的.jsp文件;

<html class="no-js" lang="en"> 
    <head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <title>Foundation | Welcome</title> 
    <link rel="stylesheet" href="/sources/css/foundation.css" /> 
    <script src="/sources/js/vendor/modernizr.js"></script> 
    </head> 
    <body> 

enter image description here

enter image description here

這是我的configuratin文件

@Configuration 
    @ComponentScan("com.sprhib") 
    @EnableWebMvc 
    public class BaseTestConfig { 

     @Bean 
     public UrlBasedViewResolver setupViewResolver() { 
      UrlBasedViewResolver resolver = new UrlBasedViewResolver(); 
      resolver.setPrefix("/WEB-INF/pages/"); 
      resolver.setSuffix(".jsp"); 
      resolver.setViewClass(JstlView.class); 
      return resolver; 
     } 


      public void addResourceHandlers(ResourceHandlerRegistry registry) { 
      registry.addResourceHandler("/sources/**").addResourceLocations("/sources/"); 
     } 

    } 
+0

你是什麼意思的網頁沒有看到的CSS代碼? –

+0

您是否在dispatcher-servlet.xml文件中添加了資源配置?例如。 Ajeesh

+0

我不添加它,因爲我不使用xml配置我使用註釋配置該如何做到這一點。我的代碼就是這樣的; – EmreAltun

回答

3

web應用程序未部署的Web應用程序根。所以它有一個「上下文路徑」。訪問index.html文件是在你的web應用的根目錄的路徑,例如,其實像

http://localhost:8080/myfirstwebapp/index.html 

這是瀏覽器的地址欄中包含,並且/myfirstwebapp是上下文路徑的應用程序。

所以,如果頁面包含href="/sources/css/foundation.css",瀏覽器將嘗試從

http://localhost:8080/sources/css/foundation.css 

,而不是從

http://localhost:8080/myfirstwebapp/sources/css/foundation.css 

加載CSS文件,因此,你需要上下文路徑,預先準備所有 Web應用程序中的絕對URL。使用JSTL:

沒有JSTL:

href="${pageContext.request.contextPath}/sources/css/foundation.css" 
0

試圖直接通過與完整的URL路徑Web瀏覽器中調用這些CSS。 這取決於你在Tomcat或Web服務器中定義的應用程序路徑。

如果它映射像http://yourdomain.com/(根),它應該是http://yourdomain.com/sources/css/foundation.css,但如果它像映射或http://yourdomain.com/test東西,網址爲CSS應該是http://yourdomain.com/test/sources/css/fundations.css

您可以爲這些使用相對通行證,也可以引入PATH變量,以便始終在源代碼中創建類似http://yourdomain.com/PATH/sources/css/foundations.css的鏈接。

0

刪除//來源。這將工作

+0

只有當他正在訪問webapp根目錄下的URL時。 –

+0

是的,你是對的。這隻有在@EmreAltun將其Web應用程序映射爲ROOT –

+0

號時才起作用。即使Web應用程序是根Web應用程序,它也只適用於根目錄下的URL,即它將與/hello.jsp一起使用,但不會用於/foo/bar/hello.jsp)。 –