Не удается загрузить файлы CSS и изображения в моем приложении Spring MVC + Thymeleaf - PullRequest
1 голос
/ 07 июля 2019

Я прочитал много статей со stackoverflow и других веб-сайтов, чтобы загрузить мой css-файл и изображения в мое приложение Spring MVC. Тем не менее, я всегда получаю строгую ошибку типа MIME. (Какие виды раздражают меня сейчас.)

Мне нужна помощь, ребята !!

Я прочитал следующие статьи для решения.

1) тимелист 3 пружины 5 нагрузка css

2) Не удается загрузить мой css при использовании пружинной защиты и тимьяна

3) Невозможно добавить CSS-файл весной и тимьяна

4) SpringBoot с Thymeleaf - css не найден

5) Spring mvc проблема с загрузкой ресурсов (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) Мой 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) Просмотр (html)

Я пытаюсь загрузить свой файл css следующим образом:

<!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" />

и мой файл изображения

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

Не удалось загрузить ресурс: сервер ответил со статусом 404 () 2style.css: 1

Не удалось загрузить ресурс: сервер ответил со статусом 404 ()

Структура моей папки:

Структура папок

Где я ошибся?

1 Ответ

0 голосов
/ 07 июля 2019

Правильное имя папки src/main/resources/static, а не statics. Попробуйте обновить свою структуру до этого имени. Лучше всего будет соответствовать этому соглашению, если вы однажды перейдете на Spring Boot.

...