1

I've read many articles from stackoverflow and others websites in order to load my css file and images on my Spring MVC application. However, I always get a strict MIME type error. (Which kinds of irritates me now.)

I need help guys!!

I've read the following articles for solution.

1) thymeleaf 3 spring 5 load css

2)Can't load my css when using spring security and thymeleaf

3) Unable to add css file in spring and thymeleaf

4)SpringBoot with Thymeleaf - css not found

5)Spring mvc issue with loading of resources (images/css)

1) WebSecurityConfigApp

    @Override
    public void configure(WebSecurity web) throws Exception {
        // Enable access to my local static resources

        web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/vendor/**", "/fonts/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.eraseCredentials(true)
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
        //add our users for in memory authentication

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/index")
                .permitAll()
                .usernameParameter("userName")
                .passwordParameter("password")
                .loginProcessingUrl("/authenticate")
                .defaultSuccessUrl("/result")
                .failureUrl("/login/failure")
        ;
    }

2) My MVCConfigFile

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        //engine.addDialect(new SpringSecurityDialect());
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setOrder(1);
        return viewResolver;
    }

    /**
     * Using Custom Resource Path
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

          // Register resource handler for CSS and JS
        if (!registry.hasMappingForPattern("/resources/**")) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/resources/**")
                    .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
        }

          // Register resource handler for images
        if (!registry.hasMappingForPattern("/images/**")) {
            registry.addResourceHandler("/images/**").addResourceLocations("/images/**")
                    .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
        }
    }

3) View (html)

I am trying to load my css file in the following way:

<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <meta name="description" content=""/>
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"/>
    <meta name="generator" content="Jekyll v3.8.5"/>

    <title>Navbar Template · Bootstrap</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" th:href="@{/static/css/style.css}" type="text/css" />

and my image file

<div class="container">
    <div class="row">
        <!-- Carousal -->
        <div class="col-md-8">
            <div class="panel panel-default">
                <div class="panel-body">
                    <!--カルーセルのタグ。いじるのはオススメしない。-->
                    <div id="carousel-example" class="carousel slide" data-ride="carousel">

                        <!--ここで好きな枚数のスライドを作れる。imgタグのscr内に好きな画像を入れよう。-->
                        <div class="carousel-inner">
                                                    <!--後ろにactiveをつけたものが最初に表示されるよ。-->
                            <div class="carousel-item active">
                                <img class="d-block w-100" src="http://lorempixel.com/output/sports-q-c-1600-500-1.jpg"
                                     alt="Picture1">
                                <div class="carousel-caption">
                                    <h4>First Thumbnail</h4>
                                    <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots
                                        in a
                                        piece of classical Latin literature from 45 BC, making it over 2000 years
                                        old. </p>
                                </div>
                            </div>
                            <div class="carousel-item">
                                <img class="d-block w-100" src="http://lorempixel.com/output/sports-q-c-1600-500-3.jpg"
                                     alt="Picture2">
                            </div>
                            <div class="carousel-item">
                                <img class="d-block w-100" src="http://lorempixel.com/output/sports-q-c-1600-500-2.jpg"
                                     alt="Picture3">
                            </div>
                        </div>

                        <!--これはスライドの「進むボタン」と「戻るボタン」。いらないなら無くていい。-->
                        <a class="carousel-control-prev" href="#carousel-example" role="button" data-slide="prev">
                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                            <span class="sr-only">Previous</span>
                        </a>
                        <a class="carousel-control-next" href="#carousel-example" role="button" data-slide="next">
                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                            <span class="sr-only">Next</span>
                        </a>

                        <!--こちらはスライドの枚数や現在地がわかるあれ。いらないならn(ry-->
                                   
                        <ol class="carousel-indicators">
                            <li data-target="#carousel-example" data-slide-to="0" class="active"></li>
                            <li data-target="#carousel-example" data-slide-to="1"></li>
                            <li data-target="#carousel-example" data-slide-to="2"></li>
                        </ol>
                    </div>
                </div>
            </div>
                </div>
        <div class="col-md-2">
            <img th:src="@{/images/logo.png}"/>
        </div>
    </div>
</div>

Failed to load resource: the server responded with a status of 404 () 2style.css:1

Failed to load resource: the server responded with a status of 404 ()

My folder structure:

Folder Structure

Where did I go wrong?

1 Answer 1

0

The correct folder naming is src/main/resources/static not statics. Try updating your structure to this naming. You'll find it best to match this convention if you one day migrate to Spring Boot.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. I actually changed my folder structure to src/main/resources/static, but it still doesn't work. I somehow can't change the image on stackoverflow, but I definetely made that change.
try updating your link to th:href="@{/css/style.css}"
Can you also paste the full stack trace exactly how it appears?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.