CSS not loading in Spring Boot

前端 未结 8 2154
渐次进展
渐次进展 2020-12-05 00:12

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

相关标签:
8条回答
  • 2020-12-05 00:54

     <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]

    0 讨论(0)
  • 2020-12-05 00:55

    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>
    
    0 讨论(0)
  • 2020-12-05 00:56

    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:

    • https://github.com/spring-guides/tut-web/tree/master/6/complete
    • Spring Boot Service Template with Static Content

    Source:

    • Designing and Implementing a Web Application with Spring
    • Serving Web Content with Spring MVC
    0 讨论(0)
  • 2020-12-05 00:57

    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.

    0 讨论(0)
  • 2020-12-05 01:09

    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

    0 讨论(0)
  • 2020-12-05 01:16

    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.

    0 讨论(0)
提交回复
热议问题