In my current spring-boot project, my views have this line:
to reference a static css
Not use @EnableWebMvc if you are using spring boot and check spring sercurity.
Disabling @EnableWebMvc
helped me to resolve issue.
I use Spring-Boot 2.0.2
I still keep @EnableWebMvc
annotation in my webConfig.java
and override addResourceHandlers()
method to help browser reaches css and javascript files through http request.
This is the webapp directory's structure
.
webConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "example.com")
public class WebConfig implements WebMvcConfigurer {
// =======================================
// = Bean Config =
// =======================================
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
// =======================================
// = Override Methods =
// =======================================
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pdfs/**")
.addResourceLocations("/WEB-INF/pdfs/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/WEB-INF/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("/WEB-INF/js/");
}
}
index.jsp head tag:
<head>
<title>Title</title>
<!-- Custom styles for this template -->
<link href="css/cover.css" rel="stylesheet">
</head>
hope it helps you.
I use Spring-Boot with Thymeleaf http://www.thymeleaf.org/
This is the directory's structure like @Andy Wilkinson Response
Example
<link rel="stylesheet" href="../static/css/w3.css" th:href="@{/css/w3.css}">
You can use Thymeleaf http://www.thymeleaf.org/
Example
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="stylesheet" th:href="@{/css/signin.css}"/>
</head>
<body>
</body>
</html>
Remember to add xmlns and xmlns:th in your html tag.
Check your application.properties:
spring.resources.add-mappings=true
If that key is set to false, spring boot app will not load any resources.
In my case to reference files inside css and js folders like this:
<script src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
I had to place the folders in webapp folder. I have the following folder structure:
Myapp
-src
-main
-java
-resources
-static
-templates
-webapp
-resources
-WEB-INF
I mean if i had placed the css and js folders in resources folder (under main) it would have been:
<link href="../resources/css/carousel.css" rel="stylesheet">
<link href="../resources/css/bootstrap.min.css" rel="stylesheet">
<script src="../resources/js/bootstrap.min.js"></script>
If i place them in static folder (under resources) it doesn't work.