Spring Boot - Image assets are not being loaded even if they are permitted on WebSecurityConfig file - spring

I have recently wanted to add some image on a page within my Spring Boot application, templated with Thymeleaf.
Even other assets (js, css) are being loaded and served successfully, images inside permitted img folder is not being served, a broken image is shown on the designated page.
This is where the image resides:
src/main/resources/static/img/image.png
Excerpt from WebSecurityConfig:
.antMatchers("/css/**", "/js/**", "/img/**","/uploads/**","**/favicon.ico").permitAll()
from the HTML (tried 2 ways, one with Thymeleaf and one without using th prefix):
<img class="featurette-image pull-left" th:src="#{../static/img/image.png}" />
<img src="../static/img/image.png"/>
Please guide me on how to proceed?
Ps: I am using Java DSL, instead xml based configuration.
I've made the search and and seen a couple solutions did not fit my situation. (Checked answers on these before:
Spring Security Thymleaf static resources don't load
when spring security enabled, resouces(css or js) can't be loaded
HTML Image not displaying, while the src url works
)

You don't need "static" in your reference to the image, because Spring Boot by default adds those paths to the classpath (source):
/META-INF/resources/
/resources/
/static/
/public/
So your reference to the file should be directly:
th:src="#{/img/image.png}"

Related

How to load corectly image in thymeleaf (spring boot project)?

I want to display the image after an error has occurred in my spring boot application. I read the documentation and tried several ways and it still doesn't work.
I read the documentation and tried several ways and it still doesn't work.
I try this:
<img th:src="#{/images/error_image.jpg}"/>
and this:
<img src="../static/images/error_image.jpg" th:width="1000" th:src="#{/images/error_image.jpg}"/>
This is my project structure:
project structure
Hovering over a photo with ctrl directs me to a photo, so the path is good.
link
but all the time I see this:
error
[EDIT]
The issue is with below controller method, you should provide mapping below.
#GetMapping // add mapping here
public String showSignUpForm()
{
return "register";
}
Make sure static resource is not configured to different path other static/ at your end.
If you have below configuration in application.properties, remove it.
spring.resources.static-locations=
Make sure you have below configurations in application.properties, spring boot's auto-configuration will set it to resource/static/
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
It's not an issue but still, change /images/ to images/
<img src="../static/images/error_image.jpg" th:width="1000" th:src="#{images/error_image.jpg}"/>

Thymeleaf +Spring Boot can't find files (FileNotFoundException)

This is a bit of a silly and frustrating one:
The #Configuration is taken from a tutorial website or forum and in it a
ServletContextTemplateResolver thymeleafTemplateResolver
is created using the ServletContext provided by spring boot.
When requested, a FileNotFoundException is thrown, despite the file being in the configured resources folder.
How do I get it to find the file / load it from the resources?
For thymeleaf to resolve the classpath resources, you need to configure a ClassLoaderTemplateResolver. (You were using a ServletContextTemplateResolver)
Also check that setPrefix is set to the correct folder, eg. "/thymeleaf/" if your documents are in resources/thymeleaf/ and that setSuffix is set to ".html" (or whatever your preferred file suffix is)
To also serve static content, you can extend WebMvcConfigurer and override addResourceHandlers, to then do e.g.
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
assuming a static folder in your resources.
(Spring controllers take precedence here)

Thymeleaf: can't load js and css when direct access the page

Updated: to describe the question more clearly
I create a web applicaiton with spring boot and thymeleaf, everything works fine if I open the login page, then login, then head for the management module or reports module sequently.
The proleam occurs when I type the url locahost:8080/send/kf/index(needs to authenticate, but I have open access to all in customized filter) in the browser, the page loads without js and css. In debug mode, I saw /send/kf was unexpectly put into the path like the following. I can get the resource if I access localhost:8080/assets/avatars/avatar.png.
The following is the folder structure I put my static resources. How could /send/kf automatically added into the url, please help me solve this problem. Thanks!
you can use spring.resources.static-locations in your application.properties file
spring.resources.static-locations=classpath:/resources/css/
spring.mvc.static-path-pattern=/resources/**
this is taken form documentation
Note:Static resources, like JavaScript or CSS, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at "/static" (or "/public")
Using /assets/ instead of assets/ fixes the issue, as otherwise it's a relative url that's supposed to get added to the end of existing url.
I find a solution for this question. I don't know how /send/kf is put into the url for the static resources, but I think if I put the controller mapping under the root path, this problem should avoid. As I think, the url is correct and resources can load successfully.
#Controller
public class ManualMessageController {
#Autowired
private MsgTemplateRepository msgTemplateRepository;
#RequestMapping("/manualMsg")
public String manualMsg(Model model){
model.addAttribute("msgTemplateList", msgTemplateRepository.findByStatus(1));
return "manualMessage";
}
}
updated:
The right solution is to use absolute path rather than relative path in the project. So change assets/css to /assets/css works.

Spring Web Flux cannot resolve path to static content

I am using Spring Boot 2.0.0 M1 with WebFlux to build my sample web application. After succeeding with REST endpoints I've decided to add some views to my application. I've decided to use Thymeleaf 3.x version. I know that Spring serves static content from 4 default location:
/META-INF/resources/
/resources/
/static/
/public/
I've decided to go with second example so my css file is in /resources/static/css/. However after loading my page .css file was not found.
This is a screenshot from my IDE:
I am not providing my own configuration for static directory I just want to use default one. What might be important is the fact that templates are loading just fine from the /resources/templates/ directory.
Css file is loaded like this:
<link data-th-href="#{css/bootstrap.min.css}" rel="stylesheet">
App is not using normal Controller class instead I've provided function as a Bean to define my router:
#Bean
RouterFunction<?> router(final GeneratorHandler generatorHandler) {
return route(GET("/generate"), handler::render);
}
Any ideas what's wrong here?
I've found the right solution. In your RouterFunction you need to use:
return resources("/**", new ClassPathResource("/static/"))
This will set your static directory to:
:classpath/static

How to import css/js in spring MVC application jsp page

I am new to spring mvc , I am creating a user registration page , there I need to put external css and import external js .
I put the script tag with src and link tag with href. But i think in Spring MVC application they will not work straight forward.
For this I added resourceservlet mapping but still it is not working
I am not able to find any way how I csn include these assets in my jsp file.
Please help me to get this one.
Regards,
Pranav
Put the CSS, JS, image files, etc., into a directory (which may contain subdirectories) in your web site, and than map the requests to that directory:
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
In this example the files are in the public-resources directory, and you refer to them using /resources in the link in your JSP.
For more information see Spring docs

Resources