0

Испробовал много вариантов с изменением путей в addResourceHandler(через classpath:/ прописывал, перемещал папку templates в webapp/WEB_INF/...), но никак не подключается css. При первом редактировании стили сработали, но не обновляются.

введите сюда описание изображения

MvcConfig.java:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    public MvcConfig() {
        super();
    }


    public void setApplicationContext(final ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

    }

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

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("Messages");
        return messageSource;
    }

    @Bean
    public DateFormatter dateFormatter() {
        return new DateFormatter();
    }



    /* **************************************************************** */
    /*  THYMELEAF-SPECIFIC ARTIFACTS                                    */
    /*  TemplateResolver <- TemplateEngine <- ViewResolver              */
    /* **************************************************************** */

    @Bean
    public SpringResourceTemplateResolver templateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(true);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }


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

nav_panel.css:

* {
    margin: 0;
    padding: 0;
}

nav ul {
    display: inline;
}

nav li {
    list-style-type: none;
}

nav li a {
    color: green;
    text-decoration: none;
}

a:hover {
    color: blue;
}

.nav_block {
    width: 100%;
    height: 50px;
    background-color: gray;
}

news.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" content="text/html">
    <title>News</title>
    <link rel="stylesheet" type="text/css" href="/static/css/nav_panel.css" th:href="@{/static/css/nav_panel.css}">
    <link rel="stylesheet" href="/static/css/news_wall.css">
    <!--<style>-->
        <!--body {-->
            <!--margin: 0;-->
            <!--padding: 0;-->
        <!--}-->

        <!--.header_block {-->
            <!--width: 100%;-->
            <!--height: 50px;-->
            <!--background-color: gray;-->
        <!--}-->
    <!--</style>-->
</head>
<body>
    <header>
        <nav>
            <ul class="nav_block">
                <li><a href="#">My page</a></li>
                <li><a href="/news">News</a></li>
                <li><a href="/news/create_news_form">Create news</a></li>
                <li><a href="#">Messages</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section>
            <table>
                <tr class="tt">
                    <th>Title</th>
                    <th>Description</th>
                    <th>Date of Created</th>
                    <th>Author</th>
                </tr>
                <tr th:each="news : ${allNews}">
                    <td th:text="${news.title}"></td>
                    <td th:text="${news.description}"></td>
                    <td th:text="${#dates.format(news.dateOfCreation, 'yyyy-MM-dd')}"></td>
                    <td><a href="#" th:text="${news.author}"></a></td>
                </tr>
            </table>
        </section>
    </main>
    <footer></footer>
</body>
</html>

В теге link в news.html видит подпапку static/..., но стили не срабатывают

6
  • Попробуйте почистить кэш 12 ноя 2019 в 5:28
  • обычно подключается так - <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"> Без "static" и без включения в класс конфигураций. 12 ноя 2019 в 8:04
  • @notaProgrammer не помогло. 12 ноя 2019 в 15:12
  • @Алексей, так в том то и дело, что мне нужно подключить с помощью класса конфигурации. Основная цель - разобраться со Spring MVC, а не искать пути его обхода. 12 ноя 2019 в 15:14
  • это стандартный путь, а не путь обхода. 12 ноя 2019 в 16:19

1 ответ 1

0

Добавил структуру /webapp/static/css и туда же переместил html-файлы. В MvcConfig прописал registry.addResourceHandler("/static/**").addResourceLocations("/static/") и всё заработало;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.