Структура проекта: < /p>
Код: Выделить всё
src
└── main
├── java
└── resources
├── static
│ └── style.css
└── templates
└── readingList.html
< /code>
readinglist.html:
ReadingList
[*]
< /code>
style.css:
@charset "UTF-8";
body {
background-color: #f4f4f4 !important;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
padding: 20px;
color: #333;
}
.bookHeadline {
font-size: 14pt;
font-weight: bold;
color: #2c3e50;
margin-bottom: 10px;
}
.bookDescription {
font-size: 12pt;
color: #7f8c8d;
}
< /code>
контроллер: < /p>
@RequestMapping(value = "/{reader}", method = RequestMethod.GET)
public String readerBooks(@PathVariable("reader") String reader, Model model) {
List readingList = readingListRepository.findByReader(reader);
if (readingList != null) {
model.addAttribute("books", readingList);
}
System.out.println("💡 Controller method executed, preparing to render readingList.html");
return "readingList";
}
Код: Выделить всё
logging.level.org.thymeleaf=DEBUG
logging.level.org.thymeleaf.templateresolver=DEBUG
logging.level.org.thymeleaf.TemplateEngine=DEBUG
logging.level.org.springframework.web.servlet.view=DEBUG
- thymeleaf renders ardersist.html Правильно
- reffring for/style.css возвращает htttp 200
htttp 2001 /> Если я inline CSS непосредственно в HTML, стили применяются правильно - журналы подтверждают, что метод контроллера запускается и шаблон обрабатывается
- Внешний файл CSS () загружается, но не применяется
Код: Выделить всё
style.css - В инструментах Dev Browser я вижу, что style.css присутствует в вкладке «Источники», но эти образцы не влияют на страницу
< /li>
< /ol>
Что мне не хватает? < /p>
Почему браузер загружает файл css успешно, но не применять стили? Я неправильно понимаю что -то о том, как Thymeleaf или Spring Boot обслуживает статические файлы? Или это проблема безопасности браузера? < /P>
< /li>
< /ol>
Обновление: я добавил минимальный воспроизводимый пример ниже, основанный на предложениях из комментариев. />Задача Описание < /h2>
Я следую за книгой «Spring Boot in Action» (Глава 2), пытаясь создать небольшое веб -приложение Thymeleaf.) не применяется. Встроенные стили работают нормально, но стили во внешнем файле не имеют эффекта. < /P>Код: Выделить всё
style.css
Как я могу получить свой style.css < /code> для правильной загрузки?)Код: Выделить всё
src ├── main │ ├── java │ │ └── com.example.readinglist │ │ └── ReadingListController.java │ └── resources │ ├── static │ │ └── style.css │ └── templates │ └── readingList.html < /code> фрагменты кода ключей < /h2> 1. Контроллер < /h3> @Controller @RequestMapping("/") public class ReadingListController { private ReadingListRepository readingListRepository; @Autowired public ReadingListController(ReadingListRepository readingListRepository) { this.readingListRepository = readingListRepository; } @RequestMapping(value = "/{reader}", method = RequestMethod.GET) public String readerBooks(@PathVariable("reader") String reader, Model model) { List readingList = readingListRepository.findByReader(reader); if (readingList != null) { model.addAttribute("books", readingList); } System.out.println("💡 Controller executed. Ready to render readingList.html"); return "readingList"; } @RequestMapping(value = "/{reader}", method = RequestMethod.POST) public String addToReadingList(@PathVariable("reader") String reader, Book book) { book.setReader(reader); readingListRepository.save(book); return "redirect:/{reader}"; } } < /code> 2. HTML -шаблон (readingList.html)Код: Выделить всё
ReadingList Your Reading List < /code> 3. CSS -файл (resources/static/style.cssЧто я попробовалКод: Выделить всё
body { background-color: #7f8c8d !important; font-family: Arial, Helvetica, sans-serif; } < /code> 4. Application.properties < /h3> spring.application.name=SpringbootDemo logging.level.org.thymeleaf=DEBUG logging.level.org.thymeleaf.templateresolver=DEBUG logging.level.org.thymeleaf.TemplateEngine=DEBUG logging.level.org.springframework.web.servlet.view=DEBUG- Подтвержденный style.css находится в SRC/Main/Resources/Static
- Пробое оба: href = "@{/jyle.css}" href="/style.css"
- Verified the controller runs and returns the correct view
- Console prints confirm the page loads
- DevTools shows style.css fails to load with ERR_CONNECTION_REFUSED
Подробности среды
Spring Boot Version: 3.4.5 < /p>
Версия Thymeleaf: по умолчанию в пружине
java версия: 22
/>2.web
3.3.tymeLeaf
4.h2database(it в этом мини -примере)
окончательный вопрос
Почему мой стиль.>
Подробнее здесь: https://stackoverflow.com/questions/796 ... glist-html