how to use css in jsp pages

16,912

Solution 1

The webapp is not deployed as the root webapp. So it has a "context path". The path to access the index.html file which is at the root of your webapp, for example, is in fact something like

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

This is what the location bar of your browser contains, and /myfirstwebapp is the context path of your application.

So, if you page contains href="/sources/css/foundation.css", the browser will try to load the css file from

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

and not from

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

You thus need to prepend the context path to all the absolute URLs in your webapp. Using the JSTL:

href="<c:url value='/sources/css/foundation.css'/>"

Without the JSTL:

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

Solution 2

Remove the / in /sources. This will work

Share:
16,912
EmreAltun
Author by

EmreAltun

I am a software engineer and I am able to use C, C++ C# JAVA, ASP.NET, ANDROID, XCODE, QT, OPENGL, PHP, HTML, JSP ...

Updated on July 22, 2022

Comments

  • EmreAltun
    EmreAltun almost 2 years

    I am trying to use css file from my jsp pages but page does not see the css codes.

    this is my .jsp file;

    <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

    this is my configuratin file

        @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/");
            }
    
        }