29

I am new to spring frame work and spring boot.I am trying to add the static html file with CSS,javascript,js. the file structure is

PROJECT STRUCTURE

and my html file head looks like this

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>HeavyIndustry by HTML5Templates.com</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />

    <link rel="stylesheet" type="text/css" media="all" href="css/5grid/core.css" th:href="@{css/5grid/core}" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-desktop.css" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-1200px.css" />
    <link rel="stylesheet" type="text/css" href="css/5grid/core-noscript.css" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <link rel="stylesheet" type="text/css" href="css/style-desktop.css" />

    <script src="css/5grid/jquery.js" type="text/javascript"></script>
    <script src="css/5grid/init.js?use=mobile,desktop,1000px&amp;mobileUI=1&amp;mobileUI.theme=none" type="text/javascript"></script>
    <!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>

when i run the spring project only the content is shown and the CSS is not applied.then the browser show the following error in the console 404 Not Found error for the .css,.js files

some body help me to sort out this issue.Thanks in Advance.

2

8 Answers 8

39

You need to put your css in /resources/static/css. This change fixed the problem for me. Here is my current directory structure.

src
  main
    java
      controller
        WebAppMain.java
    resources
      views
        index.html
      static
        css
          index.css
          bootstrap.min.css

Here is my template resolver:

public class WebAppMain {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(WebAppMain.class);
    System.out.print("Starting app with System Args: [" );
    for (String s : args) {
      System.out.print(s + " ");
    }
    System.out.println("]");
    app.run(args);
  }


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

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

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

And just in case, here is my index.html:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Subscribe</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

        <!-- Bootstrap -->
    <link type="text/css" href="css/bootstrap.min.css" rel="stylesheet" />
    <link type="text/css" href="css/index.css" rel="stylesheet" />
</head>
<body>
<h1> Hello</h1>
<p> Hello World!</p>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
</body>
</html>
2
  • it could be interesting add information about why we must put css file inside static folder. It works for me too! Sep 14, 2016 at 11:39
  • @FernandoSanchiz I assume thats just how the framework does things. I have no idea what the why is. Sep 15, 2016 at 22:56
10

Put css files into webapp resources folder:

src/main/webapp/resources/css/ 

Configure resource handler

public class WebConfig extends WebMvcConfigurerAdapter {

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

Example projects:

Source:

3
  • 2
    Also see Spring Boot docs (probably more relevant in this particular case).
    – Dave Syer
    Jan 18, 2014 at 16:35
  • @MariuszS I have changed the folder structure as mentioned above.Now the index.html itself not loading.The Browser is showing the following error "HTTP Status 500 - Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers" Jan 20, 2014 at 5:12
  • 5
    FYI: spring boot docs discourage putting content in webapp as it's not added to executable jars by default Jul 22, 2014 at 20:43
6

This is what worked for me after many attempts:

  1. css location: /resources/static/css/stylesheet.css
  2. link path in html: th:href="@{/css/stylesheet.css}"
  3. WebSecurityConfig:
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }
    
1
  • 1
    Good sample but WebSecurityConfig is not mandatory : It run perfectly without. Dec 3, 2020 at 18:24
5

Spring Boot will attempt to look in some default locations for your views. Have a look at the following link.

http://docs.spring.io/spring-boot/docs/1.1.4.RELEASE/reference/htmlsingle/#common-application-properties

If you're building an executable jar, your resources should be placed under src/main/resources, not src/main/webapp so that they're copied into your jar at build time.

Your index.html should go under src/main/resources/templates like you've got it, but your static resources shouldn't. Spring Boot will look for your Thymeleaf views there by default. And you don't actually need to define your own view resolver for Thymeleaf, Spring Boot will set this up for you if you have the spring-boot-starter-thymeleaf dependency in your project.

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh

As mentioned by others, if you put your css in src/main/resources/static/css or src/main/resources/public/css, then referencing them from href="css/5grid..." in your HTML should work.

5

I was facing the same issues and solved it the following way:

  1. Make sure the folder you are exporting is available to the web

    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
                "classpath:/META-INF/resources/", "classpath:/resources/",
                "classpath:/static/", "classpath:/public/"
        };
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**")
                    .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
        }
    }
    

    In addition you must put your css or styles folder into your src/main/resources/(static|public|resources|META-INF/resources) folder

  2. Make sure your security policies don't block them

    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            //Web resources
            web.ignoring().antMatchers("/css/**");
            web.ignoring().antMatchers("/scripts/**");
            web.ignoring().antMatchers("/images/**");
        }
    }
    

That should be enough

2

In the case of Spring Boot, however, it’s worth mentioning how Spring Boot deals with static content. When Spring Boot’s web autoconfiguration is automatically configuring beans for Spring MVC, those beans include a resource handler that maps /** to several resource locations. Those resource locations include (relative to the root of the classpath) the following:

  1. /META-INF/resources/
  2. /resources/
  3. /static/
  4. /public/

In a conventional Maven/Gradle-built application, you’d typically put static content at src/main/webapp so that it would be placed at the root of the WAR file that the build produces. When building a WAR file with Spring Boot, that’s still an option. But you also have the option of placing static content at one of the four locations mapped to the resource handler.

1

I'm new to spring boot too and I have the same problem. I have put the correct path manually into the browser and have seen the 404 by tomcat. Then I have found a solution at: Spring-Boot ResourceLocations not adding the css file resulting in 404

Now the css file is accessible by code.

You must move the css folder to src/main/resources/static/css then the content is readable (at my local configuration).

0

 <link href="<%=request.getContextPath()%>/resources/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="<%=request.getContextPath()%>/resources/css/common.css" rel="stylesheet" media="screen">
[this is the image for my project structure. i added the webapp directory to support .jsp files.this method request.getContextPath() worked for me. Hope i help someone with this... it gets the path so long as it exists. 
Nb. You should have a resolver bean in your webconfig
`enter code here`@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new   `enter code here`InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    return resolver;
}` 
for the added directory][1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.